package com.eco.fanliapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.*;
import com.eco.fanliapp.dataoke.DaTaoKeItemInfoService;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.taobao.OrderController;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.AppOrderDetailVo;
import com.eco.fanliapp.vo.HaoDanKuItemInfo;
import com.eco.fanliapp.vo.OrderNewScheme;
import com.eco.fanliapp.vo.TbkItemInfoGetInfo;
import com.eco.fanliapp.vo.TbkOrderGetInfo.NTbkOrderDataBean;
import com.eco.fanliapp.vo.job.*;
import com.eco.fanliapp.vo.respone.DTKResponse;
import com.google.common.base.Joiner;
import com.taobao.api.response.TbkScOrderDetailsGetResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TaoBaoOrderNewServiceImpl implements ITaoBaoOrderNewService {

    private static final Logger log = LoggerFactory.getLogger(TaoBaoOrderNewServiceImpl.class);

    @SuppressWarnings({"unused", "rawtypes" })
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private IAppOrderDetailService iAppOrderDetailService;
    @Autowired
    private IUserCashschemeService userCashschemeService;
    @Autowired
    private IAppUserOrderService iAppUserOrderService;
    @Autowired
    private IAppNewsLogService iAppNewsLogService;
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private IGoodsFreeService iGoodsFreeService;
    @Autowired
    private ICommissionFreezeService iCommissionFreezeService;
    @Autowired
    private IGoodsFreeService goodsFreeService;
    @Autowired
    private IAppUserRedRewardService IAppUserRedRewardService;
    @Autowired
    private OrderController orderController;
    @Autowired
    private ITaoBaoService taobaoService;

    @Autowired
    private IAppGoodsService iAppGoodsService;

    @Autowired
    private IAppUserSearchHistoryService appUserSearchHistoryService;

    @Autowired
    private ISyUserTaskService iSyUserTaskService;

    @Autowired
    private ISyTaskTypeService iSyTaskTypeService;

    @Autowired
    private ISyUserMoneyService iSyUserMoneyService;

    @Autowired
    private IAppWxWithdrawalService iAppWxWithdrawalService;

    @Autowired
    private RedisLockService redisLockService;

    @Autowired
    private FindItemIdUtils taoBaoUtils;

    @Autowired
    private UpdateUserCommon updateUserCommon;

    @Autowired
    private DaTaoKeItemInfoService daTaoKeItemInfoService;

    @Autowired
    private ISySwitchService iSySwitchService;
    @Autowired
    private AppUserRewardSetupMapper appUserRewardSetupMapper;
    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService;
    @Autowired
    private ISyChannelGoodsService syChannelGoodsService;
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private IAppOrderDetailService appOrderDetailService;
    @Autowired
    private ICommissionFreezeService commissionFreezeService;
    @Autowired
    private AppUserOrderMapper appUserOrderMapper;
    @Autowired
    private SyChannelGoodsMapper syChannelGoodsMapper;
    @Autowired
    private GoodsFreeIntegralMapper goodsFreeIntegralMapper;
    @Autowired
    private SyUserIntegralRecordMapper syUserIntegralRecordMapper;

    /**
     * Eco API
     * 拉取付款订单
     *
     * @param session        淘客的授\权session来查订单
     * @param startTime      下单时间
     * @param pageNo         第几页 默认1，1~100
     * @param tkStatus       订单状态1: 全部订单，3：订单结算，12：订单付款， 13：订单失效，14：订单成功； 订单查询类型为‘结算时间’时，只能查订单结算状态
     * @param orderCountType 订单数据统计类型，1: 2方订单，2: 3方订单，如果不设置，或者设置为1，表示2方订单
     * @param orderQueryType 订单查询类型，创建时间“create_time”，或结算时间“settle_time”。当查询渠道或会员运营订单时，建议入参创建时间“create_time”进行查询
     * @param orderScene     订单场景类型，1:常规订单，2:渠道订单，3:会员运营订单，默认为1，通过设置订单场景类型，媒体可以查询指定场景下的订单信息，例如不设置，或者设置为1，表示查询常规订单，常规订单包含淘宝客所有的订单数据，含渠道，及会员运营订单，但不包含3方分成，及维权订单
     * @return https://open.taobao.com/api.htm?docId=38078&docType=2
     */
    @Override
    @Async("myTaskAsyncPool")
    public void getPayOrderDetail(String session, String startTime, String endTime, long pageNo, long tkStatus, long orderCountType,
                                  String orderQueryType, long orderScene, int type, String positionIndex) {
        try {
            //淘宝客获取订单信息
            String str = OrderMainNew(session, startTime, endTime, pageNo, tkStatus, orderCountType, orderQueryType, orderScene, positionIndex);
            //数据封装
            TbkScOrderDetailsGetResponse info = JsonUtils.getJsonToBean(str, TbkScOrderDetailsGetResponse.class);
            //判断是否有订单
            if (info.isSuccess() && info != null && info.getData() != null && info.getData().getResults() != null && info.getData().getResults().size() > 0) {
                //#####位点，除第一页之外，都需要传递；前端原样返回。#####
                positionIndex = info.getData().getPositionIndex();
                for (TbkScOrderDetailsGetResponse.PublisherOrderDto order : info.getData().getResults()) {
                    try {
                        //处理单个付款订单
                        this.dealOrderInfo(order, "pay");
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("付款订单处理出错" + e.getMessage());
                    }
                }

                //判断是否存在下一页
                if (info.getData().getHasNext()) {
                    getPayOrderDetail(session, startTime, endTime, pageNo + 1, tkStatus, orderCountType, orderQueryType, orderScene, type, positionIndex);
                }

            } else {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (type == 0) {
                this.countLauncherPay.countDown();
            }
        }
        return;
    }

    /**
     * 获取失效订单
     *
     * @param session
     * @param startTime
     * @param pageNo
     * @param tkStatus       13
     * @param orderCountType
     * @param orderQueryType
     * @param orderScene
     * @return
     */
    @Override
    @Async("myTaskAsyncPool")
    public void getFailOrderDetail(String session, String startTime, String endTime, long pageNo,
                                   long tkStatus, long orderCountType, String orderQueryType, long orderScene, int type, String positionIndex) {

        try {

            //获取渠道的失效订单
            String str = OrderMainNew(session, startTime, endTime, pageNo, tkStatus, orderCountType, orderQueryType, orderScene, positionIndex);

            log.info("获取到失效数据：{}", str);

            TbkScOrderDetailsGetResponse info = JsonUtils.getJsonToBean(str, TbkScOrderDetailsGetResponse.class);
            if (info != null && info.isSuccess() && info.getData() != null && info.getData().getResults() != null && info.getData().getResults().size() > 0) {
                //#####位点，除第一页之外，都需要传递；前端原样返回。#####
                positionIndex = info.getData().getPositionIndex();

                for (TbkScOrderDetailsGetResponse.PublisherOrderDto order : info.getData().getResults()) {

                    try {
                        boolean flag = this.dealOrderInfo(order, "fail");
                        if (!flag) {
                            continue;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("失效订单处理出错" + e.getMessage());
                        continue;
                    }

                    //订单处理步骤
                    String redisKeyStr = "task_order_info_deal_stype" + "==fail==" + order.getTradeId();
                    String step = null;
                    if (redisTemplateService.hasKey(redisKeyStr)) {
                        step = redisTemplateService.getTByKey(redisKeyStr, String.class);
                    }
                    if (step == null || !"5".equals(step)) {
                        //根据订单编号获取订单
                        List<AppUserOrder> userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(Long.parseLong(order.getTradeId()));

                        boolean isHasUserOrder = (userOrders != null && userOrders.size() > 0);
                        if (!isHasUserOrder) {
                            redisTemplateService.set(redisKeyStr, "5", 60L * 60 * 24 * 30);
                            continue;
                        }
                        //如果是维权订单就不处理了。
                        boolean iswqflag = (userOrders.get(0) != null && userOrders.get(0).getOrderSettleStatus() != null && (userOrders.get(0).getOrderSettleStatus() == 3 || userOrders.get(0).getMaintainType() > 0));
                        if (iswqflag) {
                            redisTemplateService.set(redisKeyStr, "5", 60L * 60 * 24 * 30);
                            continue;
                        }
                        boolean isFailOrder = (userOrders.get(0) != null && userOrders.get(0).getOrderStatus() != null && userOrders.get(0).getOrderStatus() == 13);
                        //如果是已失效订单就不处理了。
                        if (isFailOrder) {
                            redisTemplateService.set(redisKeyStr, "5", 60L * 60 * 24 * 30);
                            continue;
                        }
                        for (AppUserOrder userOrder : userOrders) {
                            //判断如果订单是无效订单，同时已经结算过3，需要从该用户的账户中扣除返佣
                            boolean isSettleOrder = (userOrder.getOrderStatus() == 3 && userOrder.getOrderSettleStatus() != null && userOrder.getOrderSettleStatus() == 2);

                            if (isSettleOrder) {
                                //扣除用户无效订单返佣
                                handleUserBalance(userOrder.getUserId(), userOrder.getCommission());
                            }
                            //判断是否存在首购红包
                            AppUserRedReward appUserRedReward = IAppUserRedRewardService.selectAppUserRedRewardById(userOrder.getOrderId(), userOrder.getUserId());
                            //查询失效订单是否有红包有红包就把红包设置成失效4
                            IAppUserRedRewardService.updateAppUserRedReward(userOrder.getOrderId(), 4);
                            if (appUserRedReward != null) {
                                //如果是首购红包,设置任务为失效状态
                                updateUserCommon.UpdateUserTaskStatus(appUserRedReward.getUserId(), 6);
                            }
                            AppUserOrder appUserOrder = new AppUserOrder();
                            appUserOrder.setTableId(userOrder.getTableId());
                            appUserOrder.setOrderStatus(13);
                            appUserOrder.setCommission(BigDecimal.valueOf(0));
                            int i2 = iAppUserOrderService.updateAppUserOrder(appUserOrder);
                            if (i2 > 0) {
                                //未付款失效订单不发消息
                                if (!org.apache.commons.lang3.StringUtils.isEmpty(order.getAlipayTotalPrice()) &&
                                        new BigDecimal(order.getAlipayTotalPrice()).compareTo(BigDecimal.ZERO) > 0) {
                                    switch (userOrder.getOrderGrade()) {
                                        case 1:
                                            //数据库中查询该订单
                                            AppOrderDetail appOrderDetail = iAppOrderDetailService.selectAppOrderDetailByTradeId(userOrder.getOrderId());
                                            iAppNewsLogService.newsType(userOrder.getUserId(),
                                                    NewsEnumLog.NEWS_ORDER_FAIL.getNewsType(),
                                                    BigDecimalUtils.Format(userOrder.getCommission()), "淘宝网",appOrderDetail.getItemTitle(), userOrder.getCommission().toString());
                                            break;
                                        case 2:
                                            iAppNewsLogService.newsType(userOrder.getUserId(),
                                                    NewsEnumLog.NEWS_ORDER_SUPER_FAIL.getNewsType(),
                                                    BigDecimalUtils.Format(userOrder.getCommission()), userOrder.getCommission().toString());
                                            break;

                                        default:
                                            break;
                                    }
                                }
                                log.info("messagemessage失效订单处理成功{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                                redisTemplateService.set(redisKeyStr, "5", 60L * 60 * 24 * 30);
                            } else {
                                log.info("messagemessage失效订单处理失败{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                            }

                        }
                    }

                }
                //判断是否存在下一页
                if (info.getData().getHasNext()) {
                    getFailOrderDetail(session, startTime, endTime, pageNo + 1, tkStatus, orderCountType, orderQueryType, orderScene, type, positionIndex);
                }

            } else {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (type == 0) {
                this.countLauncherFail.countDown();
            }
        }
        return;

    }


    /**
     * 获取成功订单
     *
     * @param session
     * @param startTime
     * @param pageNo
     * @param tkStatus       14
     * @param orderCountType
     * @param orderQueryType
     * @param orderScene
     * @return
     */
    @Override
    @Async("myTaskAsyncPool2")
    public void getSuccOrderDetail(String session, String startTime, String endTime, long pageNo,
                                   long tkStatus, long orderCountType, String orderQueryType, long orderScene, int type, String positionIndex) {

        try {
            //获取渠道的失效订单
            String str = OrderMainNew(session, startTime, endTime, pageNo, tkStatus, orderCountType, orderQueryType, orderScene, positionIndex);
            TbkScOrderDetailsGetResponse info = JsonUtils.getJsonToBean(str, TbkScOrderDetailsGetResponse.class);
            if (info.isSuccess() && info != null && info.getData() != null && info.getData().getResults() != null && info.getData().getResults().size() > 0) {
                //#####位点，除第一页之外，都需要传递；前端原样返回。#####
                positionIndex = info.getData().getPositionIndex();

                for (TbkScOrderDetailsGetResponse.PublisherOrderDto order : info.getData().getResults()) {

                    try {
                        boolean flag = this.dealOrderInfo(order, "settle");
                        if (!flag) {
                            continue;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }

                    //订单处理步骤(success 改成settle，原因是默认14的状态都改成3了，当订单状态3的时候，没必要重复走)
                    String redisKeyStr = "task_order_info_deal_stype" + "==settle==" + order.getTradeId();
                    String step = null;
                    if (redisTemplateService.hasKey(redisKeyStr)) {
                        step = redisTemplateService.getTByKey(redisKeyStr, String.class);
                    }

                    if (step == null || !"5".equals(step)) {
                        //根据订单编号获取订单
                        List<AppUserOrder> userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(Long.parseLong(order.getTradeId()));

                        boolean isHasUserOrder = (userOrders != null && userOrders.size() > 0);
                        if (!isHasUserOrder) {
                            redisTemplateService.set(redisKeyStr, "5", 60L * 60 * 24 * 30);
                            continue;
                        }

                        //如果是维权订单就不处理了。
                        boolean iswqflag = (userOrders.get(0) != null && userOrders.get(0).getOrderSettleStatus() != null && (userOrders.get(0).getOrderSettleStatus() == 3 || userOrders.get(0).getMaintainType() > 0));
                        if (iswqflag) {
                            redisTemplateService.set(redisKeyStr, "5", 60L * 60 * 24 * 30);
                            continue;
                        }
                        boolean isFailOrder = (userOrders.get(0) != null && userOrders.get(0).getOrderStatus() != null && userOrders.get(0).getOrderStatus() == 13);
                        //如果是已失效订单就不处理了。
                        if (isFailOrder) {
                            redisTemplateService.set(redisKeyStr, "5", 60L * 60 * 24 * 30);
                            continue;
                        }
                        boolean isSettleOrder = (userOrders.get(0) != null && userOrders.get(0).getOrderStatus() != null && userOrders.get(0).getOrderStatus() == 3);
                        //如果是已结算订单就不处理了。
                        if (isSettleOrder) {
                            redisTemplateService.set(redisKeyStr, "5", 60L * 60 * 24 * 30);
                            continue;
                        }

                        for (AppUserOrder userOrder : userOrders) {
                            //更新订单状态
                            AppUserOrder appUserOrder = new AppUserOrder();
                            appUserOrder.setTableId(userOrder.getTableId());
                            appUserOrder.setOrderStatus(3);
                            int i2 = iAppUserOrderService.updateAppUserOrder(appUserOrder);
                            if (i2 > 0) {
                                //处理红包和任务
                                QueryWrapper<AppUserRedReward> queryWrapper = new QueryWrapper<AppUserRedReward>();
                                queryWrapper.eq("order_id", userOrder.getOrderId()).eq("hb_status", 2);
                                List<AppUserRedReward> appUserRedRewardList = IAppUserRedRewardService.list(queryWrapper);
                                if (appUserRedRewardList == null || appUserRedRewardList.size() <= 0) {
                                    handleRedOrTask(userOrder);
                                }
                                //关联用户
                                AppUser appUser = UserMainNew(order);
                                //判断是否是免单库的商品
                                AppOrderDetail appOrderDetail = iAppOrderDetailService.selectAppOrderDetailByTradeId(Long.parseLong(order.getTradeId()));
                                if (appOrderDetail.getGoodFrees() != null && appOrderDetail.getGoodFrees() == 1) {
                                    //处理免单商品结算
                                    handleFreeGoods(userOrder, appOrderDetail, appUser);
                                } else {
                                    //处理非免单商品
                                    handleNotFreeGoods(userOrder, appOrderDetail, appUser);
                                }
                                redisTemplateService.set(redisKeyStr, "5", 60L * 60 * 24 * 30);
                            } else {
                                log.info("messagemessage结算订单处理失败{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                            }
                        }


                    }

                }
                //判断是否存在下一页
                if (info.getData().getHasNext()) {
                    getSuccOrderDetail(session, startTime, endTime, pageNo + 1, tkStatus, orderCountType, orderQueryType, orderScene, type, positionIndex);
                }
            } else {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (type == 0) {
                this.countLauncherDone.countDown();
            }
        }
        return;

    }


    /**
     * 获取结算订单
     *
     * @param session
     * @param startTime
     * @param pageNo
     * @param tkStatus       3
     * @param orderCountType
     * @param orderQueryType
     * @param orderScene
     * @return
     */
    @Override
    @Async("myTaskAsyncPool2")
    public void getSettleOrderDetail(String session, String startTime, String endTime, long pageNo, long tkStatus, long orderCountType,
                                     String orderQueryType, long orderScene, int type, String positionIndex) {

        try {
            String str = OrderMainNew(session, startTime, endTime, pageNo, tkStatus, orderCountType, orderQueryType, orderScene, positionIndex);
            TbkScOrderDetailsGetResponse info = JsonUtils.getJsonToBean(str, TbkScOrderDetailsGetResponse.class);
            if (info.isSuccess() && info != null && info.getData() != null && info.getData().getResults() != null && info.getData().getResults().size() > 0) {
                //#####位点，除第一页之外，都需要传递；前端原样返回。#####
                positionIndex = info.getData().getPositionIndex();

                for (TbkScOrderDetailsGetResponse.PublisherOrderDto order : info.getData().getResults()) {

                    try {
                        boolean flag = this.dealOrderInfo(order, "settle");
                        if (!flag) {
                            continue;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("结算订单处理出错" + e.getMessage());
                        continue;
                    }

                    //订单处理步骤
                    String redisKeyStr = "task_order_info_deal_stype" + "==settle==" + order.getTradeId();
                    String step = null;
                    if (redisTemplateService.hasKey(redisKeyStr)) {
                        step = redisTemplateService.getTByKey(redisKeyStr, String.class);
                    }

                    if (step == null || !"5".equals(step)) {
                        //根据订单编号获取订单
                        List<AppUserOrder> userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(Long.parseLong(order.getTradeId()));

                        boolean isHasUserOrder = (userOrders != null && userOrders.size() > 0);
                        if (!isHasUserOrder) {
                            redisTemplateService.set(redisKeyStr, "5", 60L * 60 * 24 * 30);
                            continue;
                        }

                        //如果是维权订单就不处理了。
                        boolean iswqflag = (userOrders.get(0) != null && userOrders.get(0).getOrderSettleStatus() != null && (userOrders.get(0).getOrderSettleStatus() == 3 || userOrders.get(0).getMaintainType() > 0));
                        if (iswqflag) {
                            redisTemplateService.set(redisKeyStr, "5", 60L * 60 * 24 * 30);
                            continue;
                        }
                        boolean isFailOrder = (userOrders.get(0) != null && userOrders.get(0).getOrderStatus() != null && userOrders.get(0).getOrderStatus() == 13);
                        //如果是已失效订单就不处理了。
                        if (isFailOrder) {
                            redisTemplateService.set(redisKeyStr, "5", 60L * 60 * 24 * 30);
                            continue;
                        }
                        boolean isSettleOrder = (userOrders.get(0) != null && userOrders.get(0).getOrderStatus() != null && userOrders.get(0).getOrderStatus() == 3);
                        //如果是已结算订单就不处理了。
                        if (isSettleOrder) {
                            redisTemplateService.set(redisKeyStr, "5", 60L * 60 * 24 * 30);
                            continue;
                        }
                        for (AppUserOrder userOrder : userOrders) {
                            //更新订单状态
                            AppUserOrder appUserOrder = new AppUserOrder();
                            appUserOrder.setTableId(userOrder.getTableId());
                            appUserOrder.setOrderStatus(3);
                            int i2 = iAppUserOrderService.updateAppUserOrder(appUserOrder);
//                            redisTemplate.opsForValue().set(redisKeyStr, "5",20, TimeUnit.MINUTES);
                            if (i2 > 0) {
                                //处理红包和任务
                                QueryWrapper<AppUserRedReward> queryWrapper = new QueryWrapper<AppUserRedReward>();
                                queryWrapper.eq("order_id", userOrder.getOrderId()).eq("hb_status", 2);
                                List<AppUserRedReward> appUserRedRewardList = IAppUserRedRewardService.list(queryWrapper);
                                if (appUserRedRewardList == null || appUserRedRewardList.size() <= 0) {
                                    handleRedOrTask(userOrder);
                                }
                                //关联用户
                                AppUser appUser = UserMainNew(order);
                                //判断是否是免单库的商品
                                AppOrderDetail appOrderDetail = iAppOrderDetailService.selectAppOrderDetailByTradeId(Long.parseLong(order.getTradeId()));
                                if (appOrderDetail.getGoodFrees() != null && appOrderDetail.getGoodFrees() == 1) {
                                    //处理免单商品结算
                                    handleFreeGoods(userOrder, appOrderDetail, appUser);
                                } else {
                                    //处理非免单商品
                                    handleNotFreeGoods(userOrder, appOrderDetail, appUser);
                                }
                                redisTemplateService.set(redisKeyStr, "5", 60L * 60 * 24 * 30);
                                log.info("messagemessage结算订单处理成功{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                            } else {
                                log.info("messagemessage结算订单处理失败{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
                            }

                        }
                    }
                }
                if (info.getData().getHasNext()) {
                    getSettleOrderDetail(session, startTime, endTime, pageNo + 1, tkStatus,
                            orderCountType, orderQueryType, orderScene, type, positionIndex);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (type == 0) {
                this.countLauncherSuccess.countDown();
            }
        }
        return;
    }

    /**
     * 订单信息处理
     *
     * @param order
     * @param type
     * @return
     */
    public boolean dealOrderInfo(TbkScOrderDetailsGetResponse.PublisherOrderDto order, String type) throws Exception {

        //redis锁-时间
        long startTimes = System.currentTimeMillis() + 1000L * 200;
        //获取锁
        if (!redisLockService.lock(order.getTradeId() + "doOrderDetailFromTBK", startTimes + "")) {
            return false;
        }
        //订单处理步骤
        String redisKeyStr = "task_order_info_deal_stype==" + type + "==" + order.getTradeId();
        Integer step = null;
        if (redisTemplateService.hasKey(redisKeyStr)) {
            String stepStr = redisTemplateService.getTByKey(redisKeyStr, String.class);
            try {
                step = Integer.parseInt(stepStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (step != null && step == 4) {
            return true;
        }
        if (step != null && step > 4) {
            return false;
        }
        log.info(type + "处理订单数据：{}", JSON.toJSONString(order));

        //关联用户
        AppUser appUser = UserMainNew(order);
        AppOrderDetail appOrderDetail = OrderDteailMainNew(order, appUser);

        //查询商品
        AppGoods appGoods = getAppgoods(appOrderDetail.getItemId().toString(), appOrderDetail);

        //判断免单并插入订单信息-app_order_detail
        appOrderDetail = this.dealOrderInfoStep1(appUser, appOrderDetail, appGoods, type);

        //判断积分兑换商品

        //是未绑定订单就结束
        if (appOrderDetail == null) {
            return false;
        }

        //分佣
        List<AppUserOrder> userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(appOrderDetail.getTradeId());

        //如果是维权订单就不处理了。
        boolean iswqflag = (userOrders != null && userOrders.size() > 0 && userOrders.get(0) != null && userOrders.get(0).getOrderSettleStatus() != null && userOrders.get(0).getOrderSettleStatus() == 3);
        if (iswqflag) {
            redisTemplateService.set(redisKeyStr, "5", 60L * 60 * 24 * 30);
            return false;
        }
        //判断是否存在分佣信息并且是否预售订单-预售订单必走分佣
        boolean preparePayOrder = isPreparePayOrder(appOrderDetail);
        if (userOrders == null || userOrders.size() <= 0) {
            boolean dealUserOrder = false;
            int status = (appOrderDetail.getGoodFrees() != null && (appOrderDetail.getGoodFrees() == 1)) ? 1 : 0;//免单商品状态
            int status_two = (appOrderDetail.getGoodFrees() != null && (appOrderDetail.getGoodFrees() == 2)) ? 2 : 0;//积分商品状态
            if (status == 1) {
                //查询免单商品信息
                GoodsFree goodsFree = iGoodsFreeService.selectByGoodsId(appOrderDetail.getItemId());
                //免单商品处理
                dealUserOrder = goFreeGoods(goodsFree, appUser, appOrderDetail, appGoods, status);
                if (dealUserOrder) {
                    redisTemplateService.set(redisKeyStr, "2", 60 * 20);
                }
            } else if (status_two == 2) {
                //查询积分商品信息
                GoodsFreeIntegral goodsFree = goodsFreeIntegralMapper.selectByGoodsId(appOrderDetail.getItemId());
                //积分商品处理
                dealUserOrder = goIntegralFree(goodsFree, appUser, appOrderDetail, appGoods, status);
                if (dealUserOrder) {
                    redisTemplateService.set(redisKeyStr, "2", 60 * 20);
                }
            } else {
                //非免单商品//走正常分佣
                dealUserOrder = goSchema(appUser, appOrderDetail, appGoods);
                if (dealUserOrder) {
                    redisTemplateService.set(redisKeyStr, "2", 60 * 20);
                }
            }
            if (!dealUserOrder) {
                return false;
            }

//            redisTemplate.opsForValue().set(redisKeyStr, "2",20, TimeUnit.MINUTES);
            //判断订单是不是免单，免单不算首购红包
            log.info("红包绑定****************");
            if (appOrderDetail.getGoodFrees() != null && appOrderDetail.getGoodFrees() != 1) {
                //首购红包绑定
                if (appOrderDetail.getAlipayTotalPrice() != null && !"".equals(appOrderDetail.getAlipayTotalPrice()) && new BigDecimal(appOrderDetail.getAlipayTotalPrice()).compareTo(new BigDecimal("5")) >= 0) {
                    //订单大于5元绑定首单红包
                    firstPurchaseRedPacket(appUser.getUserId(), order.getItemId(), Long.parseLong(order.getTradeId()));
                }
            }

            //是否给予上级6元奖励
            if(appOrderDetail.getAlipayTotalPrice().compareTo("0.01") >= 0){
                IAppUserRedRewardService.addInvitationedMoney(appUser, appOrderDetail);
            }

            //每日首购添加金币
            usetTask(appUser, appOrderDetail.getTradeId(), appOrderDetail.getTbPaidTime());//根据用户传入日期处理红包任务

			if (preparePayOrder) {
				redisTemplateService.set(redisKeyStr, "4", 60L * 60 * 24);
			}else {
				redisTemplateService.set(redisKeyStr, "4", 60L * 60 * 24 * 30);
			}
        } else if (preparePayOrder) {
            //处理预售订单分佣
            boolean flag = handlePreparePayOrder(appUser, appGoods, appOrderDetail, userOrders, true);
            //非付款状态的订单处理过一次后就不再处理分佣了。
			if (!"pay".equals(type)) {
				redisTemplateService.set(redisKeyStr, "4", 60L * 60 * 24 * 30);
			}else{
				redisTemplateService.set(redisKeyStr, "4", 60L * 60 * 2);
			}
        }else {

		}

        return true;
    }

    /**
     * 存订单信息
     *
     * @param appUser
     * @param appOrderDetail
     * @param type           0结束 1完成订单插入（判断来源） 4判断免单完成分佣 2 完成红包 3完成任务
     * @return
     */
    public AppOrderDetail dealOrderInfoStep1(AppUser appUser, AppOrderDetail appOrderDetail, AppGoods appGoods, String type) {

        //判断是否是预售订单
        boolean preparePayOrder = isPreparePayOrder(appOrderDetail);

        //默认确认收货14的订单，手动设置成已结算3
        if ("14".equals(appOrderDetail.getPayStatus())) {
            appOrderDetail.setPayStatus("3");
            //手动修改earningTime 保留联盟时间tk_earningTime
            appOrderDetail.setEarningTime(System.currentTimeMillis());
        }

        //数据库中查询该订单
        AppOrderDetail appOrderDetailDatabase = iAppOrderDetailService.selectAppOrderDetailByTradeId(appOrderDetail.getTradeId());
        if (appOrderDetailDatabase != null) {
            //赋值使用
            appOrderDetail.setBinding(appOrderDetailDatabase.getBinding());
            appOrderDetail.setBindingTime(appOrderDetailDatabase.getBindingTime());
            appOrderDetail.setDeleted(appOrderDetailDatabase.getDeleted());
            appOrderDetail.setTableCreateTime(appOrderDetailDatabase.getTableCreateTime());
            appOrderDetail.setGoodFrees(appOrderDetailDatabase.getGoodFrees());
            appOrderDetail.setItemPic(appOrderDetailDatabase.getItemPic());
            appOrderDetail.setFanliMoney(appOrderDetailDatabase.getFanliMoney());
            appOrderDetail.setBuySource(appOrderDetailDatabase.getBuySource());
            appOrderDetail.setEnabled(appOrderDetailDatabase.getEnabled());
            //如果已经处理过14的，不在重复处理
//            if("3".equals(appOrderDetail.getPayStatus()) && 14 == appOrderDetail.getTkStatus() && 0 != appOrderDetailDatabase.getEarningTime()){
//				appOrderDetail.setEarningTime(appOrderDetailDatabase.getEarningTime());
//			}

        }

        //设置商品的图片
        appOrderDetail.setItemPic(appGoods == null ? "" : appGoods.getItempic());
        if (appOrderDetail.getItemPic() == null) {
            appOrderDetail.setItemPic("http:" + appOrderDetail.getItemImg());
        }

        String redisKeyStr = "task_order_info_deal_stype==" + type + "==" + appOrderDetail.getTradeId();
        if (StringUtils.isEmpty(appUser)) {
            log.info(type + "订单关联不到用户,order={}itemId={}relationID={}", appOrderDetail.getTradeId(), appOrderDetail.getItemId(), appOrderDetail.getRelationId());
            //如果没有关联到人，不记录渠道
            appOrderDetail.setBinding(0);
            int i = iAppOrderDetailService.insertAppOrderDetail(appOrderDetail);
            if (i > 0) {
                redisTemplateService.set(redisKeyStr, "11", 60L * 60);
                log.info(type + "订单关联不到用户{}已经处理了", appOrderDetail.getTradeId());
            }
            return null;
        } else {
            if (appOrderDetailDatabase == null) {
                //查询免单商品信息
                GoodsFree goodsFree = null;
                GoodsFreeIntegral goodsFreeIntegral = null;
                SyUserIntegralRecord integralRecord = null;
                int status = 0;
                if (!preparePayOrder && "pay".equals(type)) {
                    goodsFree = iGoodsFreeService.selectByGoodsId(appOrderDetail.getItemId());
                    ServerResponse<String> serverResponse = goodsFreeService.checkHaveBuy(appUser == null ? 0 : appUser.getUserId(), 1);
                    status = serverResponse.getStatus();

                    //判断是否有积分商品
                    goodsFreeIntegral = goodsFreeIntegralMapper.selectByGoodsId(appOrderDetail.getItemId());
                    //判断是否兑换过
                    QueryWrapper<SyUserIntegralRecord> queryWrapper_one = new QueryWrapper();
                    queryWrapper_one.eq("user_id", appUser.getUserId());
                    queryWrapper_one.eq("oper_binding_goods_id", appOrderDetail.getItemId());
                    queryWrapper_one.isNull("oper_binding_order");
                    integralRecord = syUserIntegralRecordMapper.selectOne(queryWrapper_one);
                }
                //如果是用户首单并且免单商品，记录免单状态-----并且不是预售订单
                boolean isGoodFree = (goodsFree != null && status == 515 && appUser != null && goodsFree.getNumber() > 0);
                boolean isInvitationFree = (goodsFreeIntegral != null && appUser != null && integralRecord != null);
                if (isGoodFree) {
                    appOrderDetail.setGoodFrees(1L);
                } else if (isInvitationFree) {
                    appOrderDetail.setGoodFrees(2L);
                } else {
                    appOrderDetail.setGoodFrees(0L);
                }
                //redis获取订单来源
                String s = addBuySource(appUser.getUserId(), appOrderDetail.getItemId());
                appOrderDetail.setBuySource(s);
                appOrderDetail.setBindingTime(new Date());
                appOrderDetail.setBinding(1);

                int i = iAppOrderDetailService.insertAppOrderDetail(appOrderDetail);
                log.info(type + "订单{}入库-result={}", appOrderDetail.getTradeId(), i);
                if (i > 0 && appOrderDetail.getGoodFrees() != null && appOrderDetail.getGoodFrees() == 1) {
                    //将订单次数加一的同时库存减一,将免单商品减去1
                    int i1 = iGoodsFreeService.updateTotalOrdersByGoodsId(goodsFree.getId());
                    log.info(type + "订单{}入库成功免单商品减一--i1={}", appOrderDetail.getTradeId(), i1);
                } else if (i > 0 && appOrderDetail.getGoodFrees() != null && appOrderDetail.getGoodFrees() == 2) {
                    //修改绑定订单
                    SyUserIntegralRecord syUserIntegralRecord = new SyUserIntegralRecord();
                    syUserIntegralRecord.setOperBindingOrder(appOrderDetail.getTradeId());
                    syUserIntegralRecord.setTableId(integralRecord.getTableId());
                    syUserIntegralRecordMapper.updateById(syUserIntegralRecord);
                }
            } else {
                int i = iAppOrderDetailService.insertAppOrderDetail(appOrderDetail);
                log.info(type + "订单{}入库-result={}", appOrderDetail.getTradeId(), i);
            }
            redisTemplateService.set(redisKeyStr, "1", 60L * 20);
        }
        return appOrderDetail;
    }

    /**
     * 判断是为预售订单
     *
     * @param appOrderDetail
     * @return
     */
    public boolean isPreparePayOrder(AppOrderDetail appOrderDetail) {
        //判断是预售订单
        if (
                com.eco.fanliapp.utils.StringUtils.isNotNull(appOrderDetail.getTbDepositTime())
                        && com.eco.fanliapp.utils.StringUtils.isNotNull(appOrderDetail.getTkDepositTime())
                        && !"--".equals(appOrderDetail.getTkDepositTime())
                        && !"--".equals(appOrderDetail.getTbDepositTime())
                        && com.eco.fanliapp.utils.StringUtils.isNotNull(appOrderDetail.getDepositPrice())

        ) {
            return true;
        }
        return false;
    }


    /**
     * 判断是否是首购，绑定首单红包，免单不算首单
     *
     * @param userId
     * @param itemId
     * @param tradeId
     */
    public void firstPurchaseRedPacket(Long userId, Long itemId, Long tradeId) {
        //判断用户是否完成了首购
//        String isFistBuyRedPacket = redisTemplateService.getTByKey("firstPurchaseRedPacket" + "_" + userId, String.class);
//        if(!StringUtils.isEmpty(isFistBuyRedPacket)){
//            return;
//        }
        //如果未完成首购任务，那就先获取锁  (redis锁-时间 (10秒))
        long startTimes = System.currentTimeMillis() + 1000 * 60;
        if (!redisLockService.lock("user_order_first_task_lock_" + userId, startTimes + "")) {
            log.info("用户userid{}首购任务", userId);
            return;
        }
        //判断用户是否存在首购红包
        QueryWrapper<AppUserRedReward> queryWrapper = new QueryWrapper<AppUserRedReward>();
        queryWrapper.eq("user_id", userId).eq("hb_type", 3).eq("hb_status", 1);
        AppUserRedReward appUserRedReward = IAppUserRedRewardService.getOne(queryWrapper);
        if (appUserRedReward == null) {
            return;
        }
     /*   //判断红包是否过期
        AppUserRewardSetup rewardSetup = null;
        if (redisTemplateService.hasKey("AppUserRewardSetup")) {
            rewardSetup = redisTemplateService.getTByKey("AppUserRewardSetup", AppUserRewardSetup.class);
        } else {
            rewardSetup = appUserRewardSetupMapper.selectByPrimaryKey(1);
            redisTemplateService.set("AppUserRewardSetup", rewardSetup, 60 * 60);
        }*/
        //任务红包没有起用过并且当前时间小于红包使用期限
//        if ((System.currentTimeMillis() - appUserRedReward.getCreateTime()) < rewardSetup.getTaskRedMoneyInvalidTime() * 24L * 60 * 60 * 1000L) {
        Integer count = 0;
        Calendar cale = Calendar.getInstance();
        int hour = cale.get(Calendar.HOUR_OF_DAY);
        //先从缓存中搜索记录
        String redisKeyStr = "AppUserSearchHistory_" + hour;//当前小时
        if (redisTemplate.hasKey(redisKeyStr)) {
            Map<String, Set<String>> searchMap = (Map) redisTemplate.opsForValue().get(redisKeyStr);
            if (searchMap != null && searchMap.size() > 0) {
                Set<String> userSet = searchMap.get(String.valueOf(userId));
                if (userSet != null && userSet.size() > 0) {
                    if (userSet.contains(String.valueOf(itemId))) {
                        count = 1;
                    }
                }
            }
        }
        if (count == 0) {
            //判断用户是否精准搜索过该商品
            QueryWrapper<AppUserSearchHistory> searchHistoryQueryWrapper = new QueryWrapper<AppUserSearchHistory>();
            searchHistoryQueryWrapper.eq("user_id", userId).eq("item_id", itemId);
            count = appUserSearchHistoryService.count(searchHistoryQueryWrapper);
        }

        if (count > 0) {
            //首次绑定订单，修改新人任务红包状态
            AppUserRedReward appUserRedRewardNew = new AppUserRedReward();
            appUserRedRewardNew.setTableId(appUserRedReward.getTableId());
            appUserRedRewardNew.setHbStatus(7);
            appUserRedRewardNew.setOrderId(tradeId);
            IAppUserRedRewardService.updateById(appUserRedRewardNew);
            //增加或修改任务日志及状态
            updateUserCommon.UpdateUserTaskStatus(appUserRedReward.getUserId(), 3);
            //设置首购标识
            redisTemplateService.set("firstPurchaseRedPacket" + "_" + userId, "完成首购", 60 * 60 * 24);

        }
//    }
    }

    /**
     * 普通分佣方案走这里
     *
     * @param appUser
     * @param appOrderDetail
     * @param appGoods
     * @return
     */
    public boolean goSchema(AppUser appUser, AppOrderDetail appOrderDetail, AppGoods appGoods) {

        //拿到用户佣金比例和用户返佣信息
        OrderNewScheme orderNewScheme = handleCustomerMoney(appUser, appOrderDetail);

        Integer orderScale = orderNewScheme.getOrderScale();//下单用户佣金
        Integer twoParentScale = orderNewScheme.getTwoParentScale();//上上级佣金
        Integer parentScale = orderNewScheme.getParentScale();//上级佣金
        BigDecimal customerMoney = orderNewScheme.getCustomerMoney();//普通分佣方案

        CommissionFreeze commissionFreeze = commissionFreezeService.selectByPrimaryKey(2, 1);
        AppUserOrder appUserOrder = new AppUserOrder();
        appUserOrder.setOrderId(appOrderDetail.getTradeId());
        appUserOrder.setOrderStatus(12);
        appUserOrder.setOrderSettleStatus(1);

        appUserOrder.setUserId(appUser.getUserId());
        appUserOrder.setTaobaoUserId(Long.valueOf(appUser.getTaobaoUserId() == null ? 0L : appUser.getTaobaoUserId()));
        appUserOrder.setOrderGrade(1);
        appUserOrder.setCommission(customerMoney.
                compareTo(BigDecimal.valueOf(0.01)) < 0 ?
                BigDecimal.valueOf(0.01) : BigDecimalUtils.Format(customerMoney));
        appUserOrder.setSpareMoney((customerMoney.
                compareTo(BigDecimal.valueOf(0.01)) < 0 ?
                BigDecimal.valueOf(0.01) : BigDecimalUtils.Format(customerMoney)).add(BigDecimalUtils.Format(appGoods == null ? 0d : appGoods.getCouponmoney())));
        //正常分佣冻结时间
        appUserOrder.setFreezeDay(commissionFreeze.getDelaydays());
        //是否是固定返(1固定返)
        appUserOrder.setOrderType(orderNewScheme.getOrderType() == null ? 0 : 1);
        int i2 = iAppUserOrderService.insertAppUserOrder(appUserOrder);
        log.info("插入用户订单中间表数据是否成功{},：用户id：{}:订单{}: {}", i2, appUser.getUserId(), appOrderDetail.getTradeId(), appOrderDetail.getTkStatus());
        if (i2 > 0) {
            if (appOrderDetail.getTkStatus() != 13) {
                try {
                    iAppNewsLogService.newsType(appUser.getUserId(), NewsEnumLog.NEWS_ORDER_PAY.getNewsType(),
                            appUserOrder.getCommission(),"淘宝网", appGoods == null ? "" : appGoods.getItemshorttitle(), (appUserOrder.getCommission().add(new BigDecimal(appGoods == null ? "0" : appGoods.getCouponmoney() + ""))).toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("付款订单{}入关联库成功发消息异常:status{}", appOrderDetail.getTradeId(), appOrderDetail.getTkStatus());
                } finally {
                    log.info("付款订单{}入关联库成功:status{}", appOrderDetail.getTradeId(), appOrderDetail.getTkStatus());
                }
            }
        } else {
            log.error("付款订单{}入关联库失败:status{}", appOrderDetail.getTradeId(), appOrderDetail.getTkStatus());
        }
//        //如果是固定返，不给上级返佣
//        if (orderNewScheme.getOrderType() != null) {
//            return true;
//        }
//        //查询1级上级
//        AppUser parentAppUser = iAppUserService.selectSuperUserInfoBySuperInviteCode(appUser.getSuperInviteCode());
//        if (parentAppUser != null) {
//            if (parentScale != null && parentScale > 0) {
//
//                AppUserOrder appUserOrderParent = new AppUserOrder();
//                appUserOrderParent.setOrderId(appOrderDetail.getTradeId());
//                appUserOrderParent.setOrderStatus(Integer.valueOf(appOrderDetail.getPayStatus()));
//                appUserOrderParent.setOrderSettleStatus(1);
//
//                appUserOrderParent.setUserId(parentAppUser.getUserId());
//                appUserOrderParent.setTaobaoUserId(Long.valueOf(appUser.getTaobaoUserId() == null ? 0L : appUser.getTaobaoUserId()));
//                appUserOrderParent.setOrderGrade(2);
//                appUserOrderParent.setCommission(BigDecimalUtils.FanliMoney(String.valueOf(parentScale),
//                        BigDecimalUtils.Format(customerMoney)).
//                        compareTo(BigDecimal.valueOf(0.01)) < 0 ?
//                        BigDecimal.valueOf(0.01) : BigDecimalUtils.FanliMoney(String.valueOf(parentScale),
//                        BigDecimalUtils.Format(customerMoney)));
//                appUserOrderParent.setSpareMoney(appUserOrder.getSpareMoney());
//
//                int i3 = iAppUserOrderService.insertAppUserOrder(appUserOrderParent);
//                if (i3 > 0) {
//                    if (appOrderDetail.getTkStatus() != 13) {
//                        try {
//                            iAppNewsLogService.newsType(parentAppUser.getUserId(), NewsEnumLog.NEWS_ORDER_SUPER_PAY.getNewsType(),
//                                    appUserOrderParent.getCommission(), appUserOrderParent.getCommission().toString());
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                            log.info("付款订单{}一级分佣成功:status{}", appOrderDetail.getTradeId(), appOrderDetail.getTkStatus());
//                        } finally {
//                            log.info("付款订单{}一级分佣成功:status{}", appOrderDetail.getTradeId(), appOrderDetail.getTkStatus());
//                        }
//                    }
//                } else {
//                    log.error("付款订单{}一级分佣失败:status{}", i3, appOrderDetail.getTkStatus());
//                }
//            }
//        }
        return true;
    }

    /**
     * 免单商品走免单
     *
     * @param goodsFree
     * @param appUser
     * @param appOrderDetail
     * @param appGoods
     * @param status
     * @return
     */
    public boolean goFreeGoods(GoodsFree goodsFree, AppUser appUser, AppOrderDetail appOrderDetail, AppGoods appGoods, int status) {

        int i2 = 0;//数据库是否添加成功
        String logTitle = "付款";
        if (appOrderDetail.getTkStatus() == 12) {
            logTitle = "付款";
        } else if (appOrderDetail.getTkStatus() == 13) {
            logTitle = "失效";
        } else if (appOrderDetail.getTkStatus() == 3) {
            logTitle = "结算";
        } else if (appOrderDetail.getTkStatus() == 14) {
            logTitle = "完成";
        }

        //查询是否是免单库的商品如果是就总订单数加1（付款）
        if (appOrderDetail.getGoodFrees() != null && appOrderDetail.getGoodFrees() == 1 && appOrderDetail.getTkStatus() == 12) {
            log.info("获取到{}免单商品orderId={}--goodfreeId={}", logTitle, appOrderDetail.getTradeId(), goodsFree.getGoodsId());
            try {
                AppUserOrder appUserOrder = new AppUserOrder();
                appUserOrder.setOrderId(appOrderDetail.getTradeId());
                appUserOrder.setOrderStatus(12);
                appUserOrder.setOrderSettleStatus(1);
                appUserOrder.setOrderGrade(1);
                appUserOrder.setSpareMoney(BigDecimalUtils.Format(goodsFree.getFixedAmount()).add(BigDecimalUtils.Format(appGoods == null ? 0d : appGoods.getCouponmoney())));
                appUserOrder.setUserId(appUser.getUserId());
                appUserOrder.setTaobaoUserId(Long.valueOf(appUser.getTaobaoUserId()));
                appUserOrder.setCommission(BigDecimalUtils.Format(goodsFree.getFixedAmount()));
                //免单商品冻结10天
                appUserOrder.setFreezeDay(8);
                i2 = iAppUserOrderService.insertAppUserOrder(appUserOrder);
                //免单增加商品
                if (i2 > 0) {
                    BigDecimal bigDecimal = new BigDecimal("0");
                    if (!StringUtils.isEmpty(appGoods)) {
                        bigDecimal = new BigDecimal(appGoods.getCouponmoney()).add(new BigDecimal(appOrderDetail.getAlipayTotalPrice() == null ? "0" : appOrderDetail.getAlipayTotalPrice()));
                    }
                    iAppNewsLogService.newsType(appUser.getUserId(), NewsEnumLog.NEWS_ORDER_PAY.getNewsType(),
                            BigDecimalUtils.Format(goodsFree.getFixedAmount()),"淘宝网", goodsFree.getGoodsTitle(), BigDecimalUtils.Format(bigDecimal).toString());
                    log.info("{}库付款订单{}入关联库成功", logTitle, appOrderDetail.getTradeId());
                } else {
                    log.error("{}库付款订单{}入关联库失败", logTitle, appOrderDetail.getTradeId());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (i2 > 0) {
            return true;
        }
        return false;
    }

    /**
     * 积分商品走免单
     *
     * @param goodsFree
     * @param appUser
     * @param appOrderDetail
     * @param appGoods
     * @param status
     * @return
     */
    public boolean goIntegralFree(GoodsFreeIntegral goodsFree, AppUser appUser, AppOrderDetail appOrderDetail, AppGoods appGoods, int status) {

        int i2 = 0;//数据库是否添加成功
        String logTitle = "付款";
        if (appOrderDetail.getTkStatus() == 12) {
            logTitle = "付款";
        } else if (appOrderDetail.getTkStatus() == 13) {
            logTitle = "失效";
        } else if (appOrderDetail.getTkStatus() == 3) {
            logTitle = "结算";
        } else if (appOrderDetail.getTkStatus() == 14) {
            logTitle = "完成";
        }

        //查询是否是免单库的商品如果是就总订单数加1（付款）
        if (appOrderDetail.getGoodFrees() != null && appOrderDetail.getGoodFrees() == 2 && appOrderDetail.getTkStatus() == 12) {
            log.info("获取到{}免单商品orderId={}--goodfreeId={}", logTitle, appOrderDetail.getTradeId(), goodsFree.getGoodsId());
            try {
                AppUserOrder appUserOrder = new AppUserOrder();
                appUserOrder.setOrderId(appOrderDetail.getTradeId());
                appUserOrder.setOrderStatus(12);
                appUserOrder.setOrderSettleStatus(1);
                appUserOrder.setOrderGrade(1);
                appUserOrder.setSpareMoney(BigDecimalUtils.Format(goodsFree.getFixedAmount()).add(BigDecimalUtils.Format(appGoods == null ? 0d : appGoods.getCouponmoney())));
                appUserOrder.setUserId(appUser.getUserId());
                appUserOrder.setTaobaoUserId(Long.valueOf(appUser.getTaobaoUserId()));
                appUserOrder.setCommission(BigDecimalUtils.Format(goodsFree.getFixedAmount()));
                //商品冻结8天
                appUserOrder.setFreezeDay(8);
                i2 = iAppUserOrderService.insertAppUserOrder(appUserOrder);
                //增加商品
                if (i2 > 0) {
                    BigDecimal bigDecimal = new BigDecimal("0");
                    if (!StringUtils.isEmpty(appGoods)) {
                        bigDecimal = new BigDecimal(appGoods.getCouponmoney()).add(new BigDecimal(appOrderDetail.getAlipayTotalPrice() == null ? "0" : appOrderDetail.getAlipayTotalPrice()));
                    }
                    iAppNewsLogService.newsType(appUser.getUserId(), NewsEnumLog.NEWS_ORDER_PAY.getNewsType(),
                            BigDecimalUtils.Format(goodsFree.getFixedAmount()),"淘宝网", goodsFree.getGoodsTitle(), BigDecimalUtils.Format(bigDecimal).toString());
                    log.info("积分商品{}库付款订单{}入关联库成功", logTitle, appOrderDetail.getTradeId());
                } else {
                    log.error("积分商品{}库付款订单{}入关联库失败", logTitle, appOrderDetail.getTradeId());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (i2 > 0) {
            return true;
        }
        return false;
    }

    /**
     * 获取商品信息
     *
     * @param itemId
     * @param order
     * @return
     */
    @Override
    public AppGoods getAppgoods(String itemId, AppOrderDetail order) {

        AppGoods appGoods = null;
        try {
            HaoDanKuItemInfo haoDanKuItemInfo = taoBaoUtils.getHaoDanKuItemId(itemId);
            log.info("拉取商品不存在去好单库拉取商品结果{}--{}", order.getTradeId(), haoDanKuItemInfo == null ? null : haoDanKuItemInfo.getCode());
            if (haoDanKuItemInfo != null && haoDanKuItemInfo.getCode() == 1 && haoDanKuItemInfo.getData() != null) {
                appGoods = new AppGoods();
                HaoDanKuItemInfo.DataBean data = haoDanKuItemInfo.getData();
                appGoods.setItempic(data.getItempic());
                appGoods.setItemtitle(data.getItemshorttitle());
                appGoods.setItemshorttitle(data.getItemshorttitle());
                appGoods.setCouponmoney(Double.valueOf(data.getCouponmoney() == null ? "0" : data.getCouponmoney()));
            } else {
                DTKResponse dtkResponse = daTaoKeItemInfoService.itemInfoByItemId(itemId);
                log.info("拉取商品不存在去大淘客拉取商品结果{}--{}", order.getTradeId(), dtkResponse == null ? null : dtkResponse.getCode());
                if (dtkResponse != null && dtkResponse.getCode() == 1 && dtkResponse.getData() != null) {
                    DTKResponse.DataBean data = dtkResponse.getData();
                    appGoods = new AppGoods();
                    appGoods.setItempic(data.getMainPic());
                    appGoods.setItemtitle(data.getDtitle());
                    appGoods.setItemshorttitle(data.getDtitle());
                    appGoods.setCouponmoney(Double.valueOf(data.getCouponPrice() == null ? "0" : data.getCouponPrice()));
                }
            }
            if (appGoods == null) {
                appGoods = iAppGoodsService.findAppGoodsByItemId(itemId);
            }
            if (appGoods == null) {
                try {
                    ServerResponse<List<TbkItemInfoGetInfo.NTbkItem>> response = taobaoService.getSearchItemIdDetail(itemId);
                    if (response != null && response.getStatus() == 200) {
                        for (TbkItemInfoGetInfo.NTbkItem item : response.getData()) {
                            appGoods = new AppGoods();
                            appGoods.setItempic(item.getPictUrl());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    appGoods = null;
                }
            }

            if (appGoods == null) {
                appGoods = new AppGoods();
            }
            if (com.eco.fanliapp.utils.StringUtils.isNull(appGoods.getItempic())) {
                appGoods.setItempic("http:" + order.getItemImg());
            }
            if (com.eco.fanliapp.utils.StringUtils.isNull(appGoods.getItemtitle())) {
                appGoods.setItemtitle(order.getItemTitle());
                appGoods.setItemshorttitle(order.getItemTitle());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("查询商品报错itmeid={}orderId={}", itemId, order.getTradeId());
        }
        return appGoods;
    }

    /**
     * 普通分佣方案走这里
     *
     * @param appUser
     * @param appOrderDetail
     * @param appGoods
     * @return
     */
    public boolean goSchemaNew(AppUser appUser, AppOrderDetail appOrderDetail, AppGoods appGoods) {

        //拿到用户佣金比例和用户返佣信息
        OrderNewScheme orderNewScheme = handleCustomerMoney(appUser, appOrderDetail);

        Integer orderScale = orderNewScheme.getOrderScale();//下单用户佣金
        Integer twoParentScale = orderNewScheme.getTwoParentScale();//上上级佣金
        Integer parentScale = orderNewScheme.getParentScale();//上级佣金
        BigDecimal customerMoney = orderNewScheme.getCustomerMoney();//普通分佣方案

        CommissionFreeze commissionFreeze = commissionFreezeService.selectByPrimaryKey(2, 1);
        AppUserOrder appUserOrder = new AppUserOrder();
        appUserOrder.setOrderId(appOrderDetail.getTradeId());
        appUserOrder.setOrderStatus(12);
        appUserOrder.setOrderSettleStatus(1);

        appUserOrder.setUserId(appUser.getUserId());
        appUserOrder.setTaobaoUserId(Long.valueOf(appUser.getTaobaoUserId() == null ? 0L : appUser.getTaobaoUserId()));
        appUserOrder.setOrderGrade(1);
        appUserOrder.setCommission(customerMoney.
                compareTo(BigDecimal.valueOf(0.01)) < 0 ?
                BigDecimal.valueOf(0.01) : BigDecimalUtils.Format(customerMoney));
        appUserOrder.setSpareMoney((customerMoney.
                compareTo(BigDecimal.valueOf(0.01)) < 0 ?
                BigDecimal.valueOf(0.01) : BigDecimalUtils.Format(customerMoney)).add(BigDecimalUtils.Format(appGoods == null ? 0d : appGoods.getCouponmoney())));
        //正常分佣冻结时间
        appUserOrder.setFreezeDay(commissionFreeze.getDelaydays());
        //是否是固定返(1固定返)
        appUserOrder.setOrderType(orderNewScheme.getOrderType() == null ? 0 : 1);
        int i2 = iAppUserOrderService.insertAppUserOrder(appUserOrder);
        log.info("插入用户订单中间表数据是否成功{},：用户id：{}:订单{}: {}", i2, appUser.getUserId(), appOrderDetail.getTradeId(), appOrderDetail.getTkStatus());
        if (i2 > 0) {
            if (appOrderDetail.getTkStatus() != 13) {
                try {
                    iAppNewsLogService.newsType(appUser.getUserId(), NewsEnumLog.NEWS_ORDER_PAY.getNewsType(),
                            appUserOrder.getCommission(), appGoods == null ? "" : appGoods.getItemshorttitle(), (appUserOrder.getCommission().add(new BigDecimal(appGoods == null ? "0" : appGoods.getCouponmoney() + ""))).toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("付款订单{}入关联库成功发消息异常:status{}", appOrderDetail.getTradeId(), appOrderDetail.getTkStatus());
                } finally {
                    log.info("付款订单{}入关联库成功:status{}", appOrderDetail.getTradeId(), appOrderDetail.getTkStatus());
                }
            }
        } else {
            log.error("付款订单{}入关联库失败:status{}", appOrderDetail.getTradeId(), appOrderDetail.getTkStatus());
        }
        return true;
    }

    /**
     * 扣除用户无效订单返佣
     *
     * @param userId
     * @param commission
     */
    private void handleUserBalance(Long userId, BigDecimal commission) {
        log.info("扣除无效用户返佣，用户id：{},扣除金额：{}", userId, commission);

        AppUser appUser = appUserService.selectAppUserByUserId(userId);
        if (appUser != null && commission != null && appUser.getBalance() != null) {
            BigDecimal balance = appUser.getBalance();
            BigDecimal newBalance = balance.subtract(commission);
            log.info("扣除无效用户id：{},返佣后金额：{}", userId, newBalance);

            appUser.setBalance(newBalance);
            appUserService.updateById(appUser);

        }

    }

    /**
     * 处理预付款订单订单金额变动问题
     *
     * @param appUser
     * @param appGoods
     * @param order
     * @param userOrders
     */
    public boolean handlePreparePayOrder(AppUser appUser, AppGoods appGoods, AppOrderDetail order, List<AppUserOrder> userOrders, boolean isNeedSend) {

		boolean flag = false;
        //订单金额变动，第二次处理预售订单
        if (!CollectionUtils.isEmpty(userOrders)) {
            try {
                //拿到用户佣金比例和用户返佣信息
                OrderNewScheme orderNewScheme = handleCustomerMoney(appUser, order);
                Integer orderScale = orderNewScheme.getOrderScale();//下单用户佣金比例
                Integer twoParentScale = orderNewScheme.getTwoParentScale();//上上级佣金比例
                Integer parentScale = orderNewScheme.getParentScale();//上级佣金比例
                BigDecimal customerMoney = orderNewScheme.getCustomerMoney();//普通分佣方案比例


				for (AppUserOrder appUserOrder_ : userOrders) {
					//判断是否分佣金额发生了变化，如果发生了变化，就返回已处理过该笔订单了
					BigDecimal commission = customerMoney.
							compareTo(BigDecimal.valueOf(0.01)) < 0 ?
							BigDecimal.valueOf(0.01) : BigDecimalUtils.Format(customerMoney);
					if (appUserOrder_.getCommission().compareTo(commission)>0){
						flag = true;
					}

					AppUserOrder appUserOrderNew = new AppUserOrder();
                    appUserOrderNew.setTableId(appUserOrder_.getTableId());

                    if (appUserOrder_.getOrderGrade() == 1) {
                        appUserOrderNew.setCommission(commission);
                        appUserOrderNew.setSpareMoney((customerMoney.
                                compareTo(BigDecimal.valueOf(0.01)) < 0 ?
                                BigDecimal.valueOf(0.01) : BigDecimalUtils.Format(customerMoney)).add(BigDecimalUtils.Format(appGoods == null ? 0d : appGoods.getCouponmoney())));
                        int i2 = iAppUserOrderService.updateAppUserOrder(appUserOrderNew);


                        if (i2 > 0) {
                            if (isNeedSend) {
                                try {
                                    iAppNewsLogService.newsType(appUser.getUserId(), NewsEnumLog.NEWS_ORDER_PAY.getNewsType(),
                                            appUserOrderNew.getCommission(),"淘宝网", appGoods == null ? "" : appGoods.getItemshorttitle(), (appUserOrderNew.getCommission().add(new BigDecimal(appGoods == null ? "0" : appGoods.getCouponmoney() + ""))).toString());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    log.info("更新用户预售付款订单{}入关联库成功发消息异常", order.getTradeId());
                                } finally {
                                    log.info("更新用户预售付款订单{}入关联库成功", order.getTradeId());
                                }
                            }
                        } else {
                            log.error("更新用户预售付款订单{}入关联库失败", order.getTradeId());
                        }
                    }
                    //上级
                    if (appUserOrder_.getOrderGrade() == 2 && orderNewScheme.getOrderType() != 2) {
                        appUserOrderNew.setCommission(BigDecimalUtils.FanliMoney(String.valueOf(parentScale),
                                BigDecimalUtils.Format(customerMoney)).
                                compareTo(BigDecimal.valueOf(0.01)) < 0 ?
                                BigDecimal.valueOf(0.01) : BigDecimalUtils.FanliMoney(String.valueOf(parentScale),
                                BigDecimalUtils.Format(customerMoney)));
                        appUserOrderNew.setSpareMoney((customerMoney.
                                compareTo(BigDecimal.valueOf(0.01)) < 0 ?
                                BigDecimal.valueOf(0.01) : BigDecimalUtils.Format(customerMoney)).add(BigDecimalUtils.Format(appGoods == null ? 0d : appGoods.getCouponmoney())));

                        int i3 = iAppUserOrderService.updateAppUserOrder(appUserOrderNew);
                        if (i3 > 0) {
                            if (isNeedSend) {
                                try {
                                    iAppNewsLogService.newsType(appUserOrderNew.getUserId(), NewsEnumLog.NEWS_ORDER_SUPER_PAY.getNewsType(),
                                            appUserOrderNew.getCommission(), appUserOrderNew.getCommission().toString());

                                } catch (Exception e) {
                                    e.printStackTrace();
                                    log.info("更新用户预售付款订单{}一级分佣成功", order.getTradeId());
                                } finally {
                                    log.info("更新用户预售付款订单{}一级分佣成功", order.getTradeId());
                                }
                            }

                        } else {
                            log.error("更新用户预售付款订单{}一级分佣失败", i3);
                        }
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
		return flag;
    }

    /**
     * 结算免单商品
     *
     * @param userOrder
     * @param appOrderDetail
     */
    public void handleFreeGoods(AppUserOrder userOrder, AppOrderDetail appOrderDetail, AppUser appUser) throws Exception {

        //更新总返佣金
        iGoodsFreeService.updateTotalRetureAmountByGoodsId(userOrder.getTableId());

        //免单商品佣金延迟10天到账
        AppUserOrder userOrder4 = new AppUserOrder();//构建佣金延迟
        userOrder4.setLargeAmountYes(1);
        userOrder4.setLargeAmountTime(getDateTime(appOrderDetail.getEarningTime(), 8));//延迟天数毫秒
        userOrder4.setTableId(userOrder.getTableId());
        userOrder4.setOrderSettleStatus(1);
        userOrder4.setOrderStatus(3);
        userOrder4.setFreezeDay(8);
        int i3 = iAppUserOrderService.updateAppUserOrder(userOrder4);
        log.info("结算订单(免单延迟)结果", i3);
        if (i3 > 0 && isSendMsg(7)) {
            iAppNewsLogService.newsType(userOrder.getUserId(),
                    NewsEnumLog.NEWS_FREE_BIGDELAY.getNewsType(),
                    BigDecimalUtils.Format(userOrder.getCommission()), "淘宝网",appOrderDetail.getItemTitle(), userOrder.getCommission().toString());
        }

        //结算成功公众号提醒
        log.info("app_order_detail的trade_id:{}", appOrderDetail.getTradeId());
        BigDecimal commission = userOrder.getCommission();
        String commissionStr = "0";
        if (commission != null) {
            commissionStr = userOrder.getCommission().toString();
        }
        commissionStr += "元";
        String tkEarningTime = appOrderDetail.getTkEarningTime();
        if (tkEarningTime == null) {
            tkEarningTime = "暂无";
        }
        ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(appUser, "30006", appOrderDetail.getTradeId().toString(), commissionStr, tkEarningTime, appUser.getWechatNickname());
        log.info("公众号发消1息返回结果{}", JSONObject.toJSONString(result));

    }

    /**
     * 处理红包和任务
     *
     * @param userOrder
     */
    public void handleRedOrTask(AppUserOrder userOrder) {
        //判断开关是否打开
        if (userOrder.getOrderGrade() == 1) {
            AppUserRewardSetup rewardSetup = null;
            if (redisTemplateService.hasKey("AppUserRewardSetup")) {
                rewardSetup = redisTemplateService.getTByKey("AppUserRewardSetup", AppUserRewardSetup.class);
            } else {
                rewardSetup = appUserRewardSetupMapper.selectByPrimaryKey(1);
                redisTemplateService.set("AppUserRewardSetup", rewardSetup, 60 * 60);
            }
            //邀请赚钱红包（上级）
            AppUserRedReward appUserRedReward = new AppUserRedReward();
            long expireTime = DateFormatUtils.addDate(new Date(), rewardSetup.getInvitationRedMoneyExpireTime()).getTime();
            appUserRedReward.setExpireTime(expireTime);
            appUserRedReward.setOrderId(userOrder.getOrderId());
            appUserRedReward.setHbType(2);
            appUserRedReward.setHbStatus(2);
            int redMoneyInvi = IAppUserRedRewardService.updateAppUserRedRewardExpireTime(appUserRedReward);

            //首购红包（本级）
            AppUserRedReward appUserRedReward2 = new AppUserRedReward();
            long expireTime2 = DateFormatUtils.addDate(new Date(), rewardSetup.getTaskRedMoneyExpireTime()).getTime();
            appUserRedReward2.setExpireTime(expireTime2);
            appUserRedReward2.setOrderId(userOrder.getOrderId());
            appUserRedReward2.setHbType(3);
            appUserRedReward2.setHbStatus(2);
            int redMoneyTask = IAppUserRedRewardService.updateAppUserRedRewardExpireTime(appUserRedReward2);

            //增加或修改任务日志状态
            AppUserRedReward userRedReward = IAppUserRedRewardService.selectAppUserRedRewardById(userOrder.getOrderId(), userOrder.getUserId());
            if (userRedReward != null) {
                log.info("订单结算---更新日志状态红包userI{}", userRedReward.getUserId());
                updateUserCommon.UpdateUserTaskStatus(userRedReward.getUserId(), 4);
            }
            log.info("订单结算更新红包状态订单号{}用户id{}邀请赚钱红包是否成功{}任务红包是否成功{}", userOrder.getOrderId(), userOrder.getUserId(), redMoneyInvi, redMoneyTask);
        }
    }

    /**
     * 处理非免单商品结算
     *
     * @param userOrder
     * @param appOrderDetail
     */
    public void handleNotFreeGoods(AppUserOrder userOrder, AppOrderDetail appOrderDetail, AppUser appUser) throws IOException {

        //查询佣金是否符合佣金冻结设置
        CommissionFreeze freeze = null;
        if (redisTemplateService.hasKey("CommissionFreezeStuep")) {
            freeze = redisTemplateService.getTByKey("CommissionFreezeStuep", CommissionFreeze.class);
        } else {
            freeze = iCommissionFreezeService.selectByPrimaryKeyLIMIT(1);
            redisTemplateService.set("CommissionFreezeStuep", freeze, 60 * 60);
        }

        //相等返回0，大于返回1，小于返回-1
        AppUserOrder userOrder2 = new AppUserOrder();//构建佣金延迟
        BigDecimal userCommission = userOrder.getCommission();
        if (BigDecimalUtils.Format(userCommission).compareTo(BigDecimalUtils.Format(freeze.getCommissionlimit())) > 0) {
            userOrder2.setLargeAmountYes(1);
            userOrder2.setLargeAmountTime(getDateTime(appOrderDetail.getEarningTime(), freeze.getDelaydays()));//延迟天数毫秒
            userOrder2.setTableId(userOrder.getTableId());
            userOrder2.setOrderSettleStatus(1);
            userOrder2.setOrderStatus(3);
            userOrder2.setFreezeDay(freeze.getDelaydays());
            int i3 = iAppUserOrderService.updateAppUserOrder(userOrder2);
            log.info("结算订单(普通商品延迟){}", i3);
            if (i3 > 0 && isSendMsg(7)) {
                iAppNewsLogService.newsType(appUser.getUserId(), NewsEnumLog.NEWS_BIGDELAY.getNewsType(),
                        BigDecimalUtils.Format(userOrder.getCommission()), "淘宝网",appOrderDetail.getItemTitle(), userOrder.getCommission().toString());
            }
        } else {
            BigDecimal beforeBalance = appUser.getBalance();
            //根据订单id查询订单
            switch (userOrder.getOrderGrade()) {
                case 1:
                    int i3 = iAppUserService.updateAppUseraddbalance(userOrder.getUserId(), BigDecimalUtils.Format(userOrder.getCommission()));
                    log.info("message{}自己{}", userOrder.getUserId(), userOrder.getCommission());
                    log.info("普通商品补贴到账开始发送消息{}", i3);
                    if (i3 > 0) {
                        //新增用户余额变动日志记录
                        syUserMoneyLogService.addSyUserMoneyLog(userOrder.getUserId(), beforeBalance, BigDecimalUtils.Format(userOrder.getCommission()), "普通商品补贴到账", 2, 0);
                        if (isSendMsg(7)) {
                            iAppNewsLogService.newsType(userOrder.getUserId(), NewsEnumLog.NEWS_ORDER_SETTLE.getNewsType(),
                                    BigDecimalUtils.Format(userOrder.getCommission()),"淘宝网", appOrderDetail.getItemTitle(), userOrder.getCommission().toString());
                        }
                        //结算成功公众号提醒
                        log.info("app_order_detail的trade_id:{}", appOrderDetail.getTradeId());
                        BigDecimal commission = userOrder.getCommission();
                        String commissionStr = "0";
                        if (commission != null) {
                            commissionStr = userOrder.getCommission().toString();
                        }
                        commissionStr += "元";
                        String tkEarningTime = appOrderDetail.getTkEarningTime();
                        if (tkEarningTime == null) {
                            tkEarningTime = "暂无";
                        }
                        ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(appUser, "30006", appOrderDetail.getTradeId().toString(), commissionStr, tkEarningTime, appUser.getWechatNickname());
                        log.info("公众号发消1息返回结果{}", JSONObject.toJSONString(result));
                    }
                    break;
               /* case 2:
                    int i4 = iAppUserService.updateAppUseraddbalance(userOrder.getUserId(), BigDecimalUtils.Format(userOrder.getCommission()));
                    log.info("message{}2级{}", userOrder.getUserId(), userOrder.getCommission());
                    log.info("普通商品补贴到账开始发送消息{}", i4);
                    if (i4 > 0) {
                        //新增用户余额变动日志记录
                        syUserMoneyLogService.addSyUserMoneyLog(userOrder.getUserId(), beforeBalance, BigDecimalUtils.Format(userOrder.getCommission()), "普通商品2级补贴到账", 2, 0);
                        if (isSendMsg(7)) {
                            iAppNewsLogService.newsType(userOrder.getUserId(), NewsEnumLog.NEWS_ORDER_SUPER_SETTLE.getNewsType(),
                                    BigDecimalUtils.Format(userOrder.getCommission()), userOrder.getCommission().toString());
                        }
                        break;
                    }*/
                default:
                    break;
            }
            AppUserOrder userOrder3 = new AppUserOrder();//构建佣金延迟
            userOrder3.setOrderStatus(3);
            userOrder3.setOrderSettleStatus(2);
            userOrder3.setTableId(userOrder.getTableId());
            int i4 = iAppUserOrderService.updateAppUserOrder(userOrder3);
            log.info("结算订单（普通商品不延迟）已经将钱转到账i4{}", i4);
        }
    }


    @Override
    public Object testHandle(Long userId, Long tradeId) {
        AppUser appUser = appUserService.selectAppUserByUserId(userId);
        AppOrderDetail appOrderDetail = appOrderDetailService.selectAppOrderDetailByTradeId(tradeId);
        OrderNewScheme orderNewScheme = handleCustomerMoney(appUser, appOrderDetail);
        return orderNewScheme;
    }


    //处理分佣
    public OrderNewScheme handleCustomerMoney(AppUser appUser, AppOrderDetail appOrderDetail) {
        OrderNewScheme orderNewScheme = new OrderNewScheme();
        Object schme = null;
        String pubSharePreFee = appOrderDetail.getPubSharePreFee();

        //商品是否参与固定返(优先考虑固定返)
        SyChannelGoods syChannelGoods1 = syChannelGoodsMapper.selectByItemIdNew(appOrderDetail.getItemId());
        //判断用户具备固定返条件(是否购买过固定返)
        //AppUserOrder appUserOrder = appUserOrderMapper.selectOrderTypeByUser(appUser.getUserId(), appOrderDetail.getItemId());
        //判断订单付款时间与下架时间是否在区间范围之内
        if (handlerOrdertype(appUser, appOrderDetail)) {
            DecimalFormat df = new DecimalFormat("0.00");
            String fixedCommissionType = syChannelGoods1.getFixedCommissionType();
            Double aDouble = Double.valueOf(fixedCommissionType == null ? "0.00" : fixedCommissionType);

            orderNewScheme.setOrderType(1);//固定返
            orderNewScheme.setCustomerMoney(new BigDecimal(df.format(aDouble)));
            return orderNewScheme;
        } else {

            //查询商品是否走特殊分佣渠道(渠道，商品)
            SyChannelGoods syChannelGoods = syChannelGoodsService.selectByCompanyIdAndItemId(appUser, appOrderDetail.getItemId());
            if (syChannelGoods != null && syChannelGoods.getCommissionType() == 1) {
                log.info("========订单号为：{}，走特殊商品分佣渠道", appOrderDetail.getTradeId());
                //特殊分佣处理
                schme = syChannelGoodsService.getShemeNew(syChannelGoods);

            } else {
                log.info("========订单号为：{}，走普通分佣渠道", appOrderDetail.getTradeId());
                //拿到用户佣金比例(普通)
                schme = userCashschemeService.getShemeNew(appUser.getUserId(), BigDecimalUtils.Format(pubSharePreFee).doubleValue());
            }
        }


        Integer orderScale = null;
        Integer parentScale = null;
        Integer twoParentScale = null;
        //获取用户杀熟佣金比例
        if (schme instanceof AppOrderFeeScheme) {
            AppOrderFeeScheme orderFeeScheme = (AppOrderFeeScheme) schme;
            int countOrderNum = iAppUserOrderService.countBingOrderSum(appUser.getUserId());
            if (orderFeeScheme.getOneorder() > countOrderNum) {
                orderScale = orderFeeScheme.getOneorderScale();
            } else if (orderFeeScheme.getTwoorder() > countOrderNum) {
                orderScale = orderFeeScheme.getTwoorderScale();
            } else if (orderFeeScheme.getThirdorder() > countOrderNum) {
                orderScale = orderFeeScheme.getThirdorderScale();
            }
            parentScale = orderFeeScheme.getOneAgentScale();
            twoParentScale = orderFeeScheme.getTwoAgentScale();
        }
        //获取用户分佣佣金比例
        if (orderScale == null) {
            AppGeneralFeeScheme generalFeeScheme = (AppGeneralFeeScheme) schme;
            double commission = BigDecimalUtils.Format(pubSharePreFee).doubleValue();
            if (generalFeeScheme.getOnepay() >= commission) {
                orderScale = generalFeeScheme.getOnepayScale();
            } else if (generalFeeScheme.getTwopay() >= commission) {
                orderScale = generalFeeScheme.getTwopayScale();
            } else if (generalFeeScheme.getThirdpay() >= commission) {
                orderScale = generalFeeScheme.getThirdpayScale();
            } else if (generalFeeScheme.getForpay() >= commission) {
                orderScale = generalFeeScheme.getForpayScale();
            } else if (generalFeeScheme.getFivepay() >= commission) {
                orderScale = generalFeeScheme.getFivepayScale();
            } else if (generalFeeScheme.getSixpay() >= commission) {
                orderScale = generalFeeScheme.getSixpayScale();
            } else if (generalFeeScheme.getSevenpay() >= commission) {
                orderScale = generalFeeScheme.getSevenpayScale();
            }
            parentScale = generalFeeScheme.getOneAgentScale();
            twoParentScale = generalFeeScheme.getTwoAgentScale();
        }
        BigDecimal customerMoney = BigDecimalUtils.FanliMoney(String.valueOf(orderScale), BigDecimalUtils.Format(pubSharePreFee == null ? "0" : pubSharePreFee));
        orderNewScheme.setCustomerMoney(customerMoney);
        orderNewScheme.setParentScale(parentScale);
        orderNewScheme.setTwoParentScale(twoParentScale);
        orderNewScheme.setOrderScale(orderScale);

        return orderNewScheme;
    }

    public boolean handlerOrdertype(AppUser appUser, AppOrderDetail appOrderDetail) {
        //1.判断用户具备固定返条件(是否购买过固定返)
        AppUserOrder appUserOrder = appUserOrderMapper.selectOrderTypeByUser(appUser.getUserId(), appOrderDetail.getItemId());
        if (appUserOrder != null) {

            return false;
        }
        //2.商品是否参与固定返(优先考虑固定返)
        SyChannelGoods syChannelGoods = syChannelGoodsMapper.selectByItemIdNew(appOrderDetail.getItemId());
        if (syChannelGoods == null) {

            return false;
        }
        //3.商品分佣类型是否符合固定返
        if (2 != syChannelGoods.getCommissionType()) {

            return false;
        }
        //4.如果该商品已下架，判断订单付款时间与下架时间是否在区间范围之内
        if (syChannelGoods.getDeleted()) {
            //付款时间
            Long createTime = appOrderDetail.getCreateTime();
            Date orderCreateDate = new Date(createTime);
            boolean bool = DateFormatUtils.diffTimeDate(syChannelGoods.getUpdateTime(), orderCreateDate);
            return bool;
        }

        return true;
    }

    /**
     * 统一请求方法
     *
     * @param session
     * @param startTime
     * @param pageNo
     * @param tkStatus
     * @param orderScene
     * @return
     */
    private String OrderMainNew(String session, String startTime, String endTime, long pageNo,
                                long tkStatus, long orderCountType, String orderQueryType, long orderScene, String positionIndex) {
        String str = "";
        TbkScOrderDetailsGetResponse tbkScOrderDetailsGetResponse = orderController.orderDetailsNew(session, startTime, endTime, pageNo, tkStatus, orderCountType, orderQueryType, orderScene, positionIndex);
        if (tbkScOrderDetailsGetResponse != null) {
            str = JSON.toJSONString(tbkScOrderDetailsGetResponse);
        }
        return str;
    }

    /**
     * 获取用户信息
     *
     * @param order
     * @return
     */
    private AppUser UserMain(NTbkOrderDataBean order) {
        AppUser appUser = null;
        if (order.getRelationId() != null && order.getRelationId() != 0) {
            appUser = iAppUserService.selectUserInfoByRelationId(order.getRelationId());
        } else if (order.getSpecialId() != null) {
            appUser = iAppUserService.selectUserInfoBySpecialId(order.getSpecialId());
        }
        if (appUser == null || appUser.getUserId() == null) {
            appUser = iAppUserService.selectUserInfoBySpecialId(order.getSpecialId());
        }
        return appUser;
    }

    /**
     * 获取用户信息
     *
     * @param order
     * @return
     */
    private AppUser UserMainNew(TbkScOrderDetailsGetResponse.PublisherOrderDto order) {
        //先根据订单id去数据库中查询app_user_order表，存在再根据app_user_order表的user_id查询用户
        AppUser appUser = null;
        QueryWrapper<AppUserOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", order.getTradeId() + "");
        queryWrapper.eq("order_grade", 1);
        AppUserOrder appUserOrder = iAppUserOrderService.getOne(queryWrapper);
        if (appUserOrder != null && appUserOrder.getUserId() != null) {
            appUser = iAppUserService.selectAppUserByUserId(appUserOrder.getUserId());
        }
        if (appUser != null && appUser.getUserId() != null && appUser.getUserId() != 0) {
            return appUser;
        }

        //根据relation_id，SpecialId查询用户
        if (order.getRelationId() != null && order.getRelationId() != 0) {
            appUser = iAppUserService.selectUserInfoByRelationId(order.getRelationId());
        } else if (order.getSpecialId() != null && order.getSpecialId() != 0) {
            appUser = iAppUserService.selectUserInfoBySpecialId(order.getSpecialId());
        }

        //根据订单号查询
        if (appUser == null || appUser.getUserId() == null || appUser.getUserId() == 0) {
            List<AppUserOrder> appUserOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(Long.parseLong(order.getTradeId()));
            if (!CollectionUtils.isEmpty(appUserOrders)) {
                for (AppUserOrder appUserOrder1 : appUserOrders) {
                    if (appUserOrder1 != null && appUserOrder1.getOrderGrade() != null && appUserOrder1.getOrderGrade() == 1) {
                        appUser = iAppUserService.selectAppUserByUserId(appUserOrder1.getUserId());
                    }
                }
            }
        }

        return appUser;
    }

    public String generateOrderDetailId(String childOrderId, String itemId) {
        return MD5Utils.createMD5(itemId + childOrderId);
    }

    /**
     * 统一接收类
     *
     * @param order
     * @return
     */
    private AppOrderDetail OrderDteailMainNew(TbkScOrderDetailsGetResponse.PublisherOrderDto order, AppUser appUser) {
        AppOrderDetail appOrderDetail = new AppOrderDetail();
        if (appUser == null || appUser.getUserId() == null || appUser.getUserId() == 0) {
            appUser = UserMainNew(order);
        }

        appOrderDetail.setAdzoneId((order.getAdzoneId() == null ? "" : order.getAdzoneId()) + "");
        appOrderDetail.setAdzoneName(order.getAdzoneName());
        appOrderDetail.setAlipayTotalPrice(order.getAlipayTotalPrice());
        appOrderDetail.setAuctionCategory(order.getItemCategoryName());
        appOrderDetail.setClickTime(order.getClickTime() == null ? 0 : DateUtils.datestr2LongByFormt(order.getTbPaidTime(), null));
        appOrderDetail.setCommission(order.getTotalCommissionFee());
        appOrderDetail.setCommissionRate(order.getTotalCommissionRate());
        appOrderDetail.setEarningTime(order.getTkEarningTime() == null ? 0 : DateUtils.datestr2LongByFormt(order.getTkEarningTime(), null));
        appOrderDetail.setCreateTime(order.getTkCreateTime() == null ? 0 : DateUtils.datestr2LongByFormt(order.getTkCreateTime(), null));
        appOrderDetail.setItemId(order.getItemId());
        appOrderDetail.setItemNum(order.getItemNum());
        appOrderDetail.setItemTitle(order.getItemTitle());
        appOrderDetail.setOrderDetailid(generateOrderDetailId(order.getTradeId(), order.getItemId().toString()));
        appOrderDetail.setOrderType(order.getOrderType());
        appOrderDetail.setPayPrice(order.getPayPrice());
        appOrderDetail.setPayStatus(order.getTkStatus().toString());
        appOrderDetail.setTkStatus(order.getTkStatus().intValue());
        appOrderDetail.setRelationId(order.getRelationId());
        appOrderDetail.setSellerNick(order.getSellerNick());
        appOrderDetail.setSellerShopTitle(order.getSellerShopTitle());
        appOrderDetail.setSiteId(order.getSiteId() == null ? "" : (order.getSiteId() + ""));
        appOrderDetail.setSiteName(order.getSiteName());
        appOrderDetail.setSpecialId(order.getSpecialId());
        appOrderDetail.setTableCreateTime(System.currentTimeMillis());
        appOrderDetail.setTableUpdateTime(System.currentTimeMillis());
        appOrderDetail.setTaobaoUserId(appUser == null ? 0 : appUser.getTaobaoUserId());
        appOrderDetail.setTotalCommissionFee(order.getTotalCommissionFee());
        appOrderDetail.setTotalCommissionRate(order.getTotalCommissionRate());
        appOrderDetail.setTradeId(Long.parseLong(order.getTradeId()));
        appOrderDetail.setTradeParentId(Long.parseLong(order.getTradeParentId()));
        appOrderDetail.setIncomeRate(order.getIncomeRate());
        appOrderDetail.setPubSharePreFee(order.getPubSharePreFee());
        appOrderDetail.setPrice(order.getItemPrice());
        appOrderDetail.setSubsidyFee(order.getSubsidyFee());
        appOrderDetail.setSubsidyRate(order.getSubsidyRate());
        appOrderDetail.setSubsidyType(order.getSubsidyType());
        appOrderDetail.setTk3rdPubId(order.getPubId());
//        appOrderDetail.setTk3rdType(order.getTk3rdType());
//        appOrderDetail.setTk3rdSiteid(order.getTk3rdSiteId());
//        appOrderDetail.setTk3rdAdzoneid(order.getTk3rdAdzoneId());
        appOrderDetail.setTerminalType(order.getTerminalType());

        appOrderDetail.setTkDepositTime(order.getTkDepositTime());
        appOrderDetail.setTbDepositTime(order.getTbDepositTime());
        appOrderDetail.setDepositPrice(order.getDepositPrice());
        appOrderDetail.setAppKey(order.getAppKey());
        appOrderDetail.setTkEarningTime(order.getTkEarningTime());
        appOrderDetail.setTbPaidTime(order.getTbPaidTime());
        appOrderDetail.setTkPaidTime(order.getTkPaidTime());
        appOrderDetail.setRefundTag(order.getRefundTag() == null ? 0 : order.getRefundTag());
        appOrderDetail.setItemImg(order.getItemImg());
        appOrderDetail.setTkOrderRole(order.getTkOrderRole() == null ? 0 : order.getTkOrderRole());
        appOrderDetail.setPubShareFee(order.getPubShareFee());
        appOrderDetail.setPubShareRate(order.getPubShareRate());
        appOrderDetail.setTkTotalRate(order.getTkTotalRate());
        appOrderDetail.setAlimamaRate(order.getAlimamaRate());
        appOrderDetail.setAlimamaShareFee(order.getAlimamaShareFee());
        appOrderDetail.setFlowSource(order.getFlowSource());
        appOrderDetail.setItemLink(order.getItemLink());
        appOrderDetail.setTkCommissionPreFeeForMediaPlatform(order.getTkCommissionPreFeeForMediaPlatform());
        appOrderDetail.setTkCommissionFeeForMediaPlatform(order.getTkCommissionFeeForMediaPlatform());
        appOrderDetail.setTkCommissionRateForMediaPlatform(order.getTkCommissionRateForMediaPlatform());

        appOrderDetail.setTkCreateTime(order.getTkCreateTime());//订单创建时间;

        log.info("message订单佣金{}，计算后佣金{}", order.getPubSharePreFee(), BigDecimalUtils.Format(order.getPubSharePreFee() == null ? "0" : order.getPubSharePreFee()));
        appOrderDetail.setFanliMoney(BigDecimalUtils.Format(order.getPubSharePreFee() == null ? "0" : order.getPubSharePreFee()));
        return appOrderDetail;
    }

    /**
     * 获取指定时间的时间戳
     * 一天是86400000
     *
     * @param start 天数
     * @return
     */
    public static long getDateTime(Long earningTime, Integer start) {
        Date paramDate = null;
        if (earningTime == null) {
            paramDate = new Date();
        } else {
            paramDate = new Date(earningTime);
        }
        return org.apache.commons.lang3.time.DateUtils.addDays(paramDate, start).getTime();
    }

    public static void main(String[] args) {

//        long current = System.currentTimeMillis();    //当前时间毫秒数
//        long startTodayTime = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();  //今天零点零分零秒的毫秒数
//        long endTodayTime = startTodayTime + 24 * 60 * 60 * 1000 - 1;  //今天23点59分59秒的毫秒数
//

//        String startTime = "2019-10-28 12:14:08";
//        Date startDate = DateUtils.datestr2Date(startTime, null);
//
//        Date zeroStartTimeByDate = DateUtils.getZeroStartTimeByDate(startDate);//传入日期当天开始时间
//        Date zeroEndTimeByDate = DateUtils.getZeroEndTimeByDate(startDate);//传入日期当天结束时间
//        String pubSharePreFee = "0.76";
//        String orderScale = "50";
//
//        BigDecimal customerMoney = BigDecimalUtils.FanliMoney(String.valueOf(orderScale), BigDecimalUtils.Format(pubSharePreFee == null ? "0" : pubSharePreFee));

    }

    /**
     * 每日首购
     */
    private void usetTask(AppUser appUser, Long tradeId, String startTime) {
        String nowDateHour = DateFormatUtils.getNowDateHour(new Date());
        //判断用户是否完成每日首购
//        String isFistBuy = redisTemplateService.getTByKey(nowDateHour + "_" + appUser.getUserId(), String.class);
//        if(!StringUtils.isEmpty(isFistBuy)){
//            return;
//        }

        //如果未完成首购，那就先获取锁  (redis锁-时间 (10秒))
        long startTimes = System.currentTimeMillis() + 1000 * 60;
        if (!redisLockService.lock("user_order_day_task_lock_" + appUser.getUserId(), startTimes + "")) {
            log.info("用户userid{}首购任务", appUser.getUserId());
            return;
        }

        if (startTime == null || "".equals(startTime)) {
            startTime = DateFormatUtils.dateToString(new Date());
        }
        //date:2019-09-26 by:zhuchao des:根据传入订单日期判断红包
        Date startDate = DateUtils.datestr2Date(startTime, null);
        Date zeroStartTimeByDate = DateUtils.getZeroStartTimeByDate(startDate);//传入日期当天开始时间
        Date zeroEndTimeByDate = DateUtils.getZeroEndTimeByDate(startDate);//传入日期当天结束时间

        long startTodayTime = zeroStartTimeByDate.getTime();//传入日期当天零点零分零秒的毫秒数
        long endTodayTime = zeroEndTimeByDate.getTime();  //传入日期当天23点59分59秒的毫秒数
        log.info("开始时间{}结束时间{}", startTodayTime, endTodayTime);
        int i = iAppOrderDetailService.selectOrderIsTodayCount(startTodayTime, endTodayTime, appUser.getTaobaoUserId());
        log.info("根据订单号查询是不是当天第一次下单订单号{}用户id:{}淘宝用户id:{}==结果{}", tradeId, appUser.getUserId(), appUser.getTaobaoUserId(), i);
        if (i <= 1) {
            //查询每日首购任务
            SyTaskType syTaskType = iSyTaskTypeService.selectSyTaskTypeById(6);
//            //增加日志
//            SyUserTask syUserTask = new SyUserTask();
//            syUserTask.setUserId(appUser.getUserId());
//            syUserTask.setTaskTypeId(syTaskType.getTableId());
//            syUserTask.setTaskType(syTaskType.getTaskType());
//            syUserTask.setTaskRewardType(syTaskType.getTaskRewardType());
//            syUserTask.setTaskStatus(5);
//            syUserTask.setTaskRewardNum(syTaskType.getTaskRewardNum());
//            syUserTask.setTaskRewardDate(new Date());
//            syUserTask.setEnable(1);
//            int syUserTaskNum = iSyUserTaskService.insertsyUserTask(syUserTask);

            //给用户加任务金币 根据用户id查询能查到修改 否则新增
//            SyUserMoney oldSyUserMoney = iSyUserMoneyService.selectByUserId(appUser.getUserId());
//            if (oldSyUserMoney == null) {
//                SyUserMoney syUserMoney = new SyUserMoney();
//                syUserMoney.setUserId(appUser.getUserId());
//                syUserMoney.setGoldBalanceAmount(syTaskType.getTaskRewardNum());
//                syUserMoney.setGoldTotalAmount(syTaskType.getTaskRewardNum());
//                syUserMoney.setEnable(1);
//                int syUserMoneyNum = iSyUserMoneyService.insertSyUserMoney(syUserMoney);
//                log.info("用户增加加金币用户id{}结果{}", appUser.getUserId(), syUserMoneyNum);
//            } else {
//                SyUserMoney syUserMoney = new SyUserMoney();
//                syUserMoney.setTableId(oldSyUserMoney.getTableId());
//                syUserMoney.setUserId(appUser.getUserId());
//                syUserMoney.setGoldBalanceAmount(syTaskType.getTaskRewardNum() + oldSyUserMoney.getGoldBalanceAmount());
//                syUserMoney.setGoldTotalAmount(syTaskType.getTaskRewardNum() + oldSyUserMoney.getGoldTotalAmount());
//                int syUserMoneyNum = iSyUserMoneyService.updateSyUserMoney(syUserMoney);
//                log.info("用户修改金币用户id{}结果{}", appUser.getUserId(), syUserMoneyNum);
//            }
            String remark = "每日首购金额到账";
            updateUserCommon.updateUserGoldExchangeMoney(appUser.getUserId(), 6, syTaskType.getTaskRewardNum(), 2, null, remark);
            //添加完成首购标识
            redisTemplateService.set(nowDateHour + "_" + appUser.getUserId(), "完成首购", 60 * 60 * 24L);
        }
    }

    /**
     * @param appUser     用户
     * @param messageType 信息类型
     *                    30001：到账提醒模板、
     *                    30002：下单成功提醒模板，
     *                    30003：收货成功模板，
     *                    30004：好友下单成功提醒
     *                    30005：邀请好友成功
     * @param amount      金额
     */
    private void weCheatMessage(AppUser appUser, String messageType, String amount) {
        try {
            log.info("公众号发消息类型{}金额{},用户{}", messageType, amount, JSONObject.toJSONString(appUser));
            ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(appUser, messageType, appUser.getWechatNickname(), DateFormatUtils.getCurrentDate(), amount, "微信");
            log.info("公众号发消息返回结果{}", JSONObject.toJSONString(result));
        } catch (Exception e) {
            e.printStackTrace();
            log.info("公众号发消息异常", e.getMessage());
        }
    }


    /**
     * 通过开关判断是否要发消息
     *
     * @return
     * @id 开关类型
     */
    private Boolean isSendMsg(int id) {
        //查询开关表是否发消息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("table_id", id);
        SySwitch sySwitch = iSySwitchService.getOne(queryWrapper);
        if (sySwitch == null) return false;
        if (sySwitch.getState() == 1) {
            log.info("消息类型{} 消息开发送消息", id);
            return true;
        }
        log.info("消息类型{} 消息关", id);
        return false;
    }


    public String addBuySource(Long userId, Long itemId) {
        //redis获取buy_source
        List<Map<Object, Object>> map = (List<Map<Object, Object>>) redisTemplate.opsForList().range("app_buy_source_" + userId, 0, -1);
        if (map.size() > 0) {
            List<String> orderSourceList = new ArrayList<>();
            for (Map orderSource : map) {
                if (orderSource.get("itemId").equals(itemId) && orderSource.get("jumpType") != null) {
                    orderSourceList.add(orderSource.get("jumpType").toString());
                }
            }
            String orderSourceStr = Joiner.on(",").join(orderSourceList);
            return orderSourceStr;
        }
        return null;
    }

    @Override
    public Boolean handleBindingOrder(AppUser appUser, AppOrderDetail appOrderDetail, AppGoods appGoods) {
        boolean bool = false;
        //免单分佣
        if (appOrderDetail.getGoodFrees() != null && appOrderDetail.getGoodFrees() == 1) {
            //查询免单商品信息
            GoodsFree goodsFree = iGoodsFreeService.selectByGoodsId(appOrderDetail.getItemId());
            bool = goBingFreeGoodsNew(appUser, appOrderDetail, appGoods, goodsFree);
        } else {
            //非免单商品
            bool = goBingNotFreeGoods(appOrderDetail, appUser, appGoods);
        }
        return bool;
    }

    @Override
    public void handlDisSettleOrderList(AppOrderDetail aod) throws Exception {
        //根据订单编号获取订单
        List<AppUserOrder> userOrders = iAppUserOrderService.selectAppUserOrderListByTradeId(aod.getTradeId());
        boolean isHasUserOrder = (userOrders != null && userOrders.size() > 0);
        if (!isHasUserOrder) {
            return;
        }

        //如果是维权订单就不处理了。
        boolean iswqflag = (userOrders.get(0) != null && userOrders.get(0).getOrderSettleStatus() != null && userOrders.get(0).getOrderSettleStatus() == 3);
        if (iswqflag) {
            return;
        }

        //如果是已失效订单就不处理了。
        boolean isFailOrder = (userOrders.get(0) != null && userOrders.get(0).getOrderStatus() != null && userOrders.get(0).getOrderStatus() == 13);
        if (isFailOrder) {
            return;
        }

        //如果是已结算订单就不处理了。
        boolean isSettleOrder = (userOrders.get(0) != null && userOrders.get(0).getOrderStatus() != null && userOrders.get(0).getOrderStatus() == 3);
        if (isSettleOrder) {
            return;
        }
        for (AppUserOrder userOrder : userOrders) {
            //更新订单状态
            AppUserOrder appUserOrder = new AppUserOrder();
            appUserOrder.setTableId(userOrder.getTableId());
            appUserOrder.setOrderStatus(3);
            int i2 = iAppUserOrderService.updateAppUserOrder(appUserOrder);
            if (i2 > 0) {
                //处理红包和任务
                QueryWrapper<AppUserRedReward> queryWrapper = new QueryWrapper<AppUserRedReward>();
                queryWrapper.eq("order_id", userOrder.getOrderId()).eq("hb_status", 2);
                List<AppUserRedReward> appUserRedRewardList = IAppUserRedRewardService.list(queryWrapper);
                if (appUserRedRewardList == null || appUserRedRewardList.size() <= 0) {
                    handleRedOrTask(userOrder);
                }
                //关联用户
                AppUser appUser = iAppUserService.selectAppUserByUserId(userOrder.getUserId());
                //判断是否是免单库的商品
                AppOrderDetail appOrderDetail = iAppOrderDetailService.selectAppOrderDetailByTradeId(aod.getTradeId());
                if (appOrderDetail.getGoodFrees() != null && appOrderDetail.getGoodFrees() == 1) {
                    //处理免单商品结算
                    handleFreeGoods(userOrder, appOrderDetail, appUser);
                } else {
                    //处理非免单商品
                    handleNotFreeGoods(userOrder, appOrderDetail, appUser);
                }
                log.info("手动修改结算订单处理成功{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
            } else {
                log.info("手动修改结算订单处理失败{}用户为{}修改的ID为{}", userOrder.getOrderId(), userOrder.getUserId(), userOrder.getTableId());
            }

        }
    }

    public Boolean goBingFreeGoodsNew(AppUser appUser, AppOrderDetail appOrderDetail, AppGoods appgoods, GoodsFree goodsFree) {
        AppUserOrder appUserOrder = null;
        try {
            //查询佣金是否符合佣金冻结设置
            CommissionFreeze freeze = null;
            if (redisTemplateService.hasKey("CommissionFreezeStuep")) {
                freeze = redisTemplateService.getTByKey("CommissionFreezeStuep", CommissionFreeze.class);
            } else {
                freeze = iCommissionFreezeService.selectByPrimaryKeyLIMIT(1);
                redisTemplateService.set("CommissionFreezeStuep", freeze, 60 * 60);
            }

            Integer tkStatus = Integer.valueOf(appOrderDetail.getPayStatus());
            //处理免单
            appUserOrder = new AppUserOrder();
            appUserOrder.setUserId(appUser.getUserId());
            appUserOrder.setTaobaoUserId(Long.valueOf(appUser.getTaobaoUserId() == null ? 0L : appUser.getTaobaoUserId()));
            appUserOrder.setOrderId(appOrderDetail.getTradeId());
            if (tkStatus == 13) {
                appUserOrder.setCommission(BigDecimalUtils.Format(0));
            } else {
                appUserOrder.setCommission(BigDecimalUtils.Format(goodsFree.getFixedAmount()));
            }
            appUserOrder.setSpareMoney(BigDecimalUtils.Format(goodsFree.getFixedAmount()).add(BigDecimalUtils.Format(appgoods == null ? 0d : appgoods.getCouponmoney())));
            appUserOrder.setOrderGrade(1);
            appUserOrder.setOrderStatus(tkStatus);
            appUserOrder.setOrderSettleStatus(1);
            appUserOrder.setFreezeDay(8);
            if (tkStatus == 3 || tkStatus == 14) {
                appUserOrder.setLargeAmountYes(1);
                appUserOrder.setLargeAmountTime(getDateTime(appOrderDetail.getEarningTime(), freeze.getDelaydays()));//延迟天数毫秒
            }
            iAppUserOrderService.insertAppUserOrder(appUserOrder);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 处理非免单商品结算
     *
     * @param appUser
     * @param appOrderDetail
     */
    public Boolean goBingNotFreeGoods(AppOrderDetail appOrderDetail, AppUser appUser, AppGoods appGoods) {

        try {
            //拿到用户佣金比例和用户返佣信息
            OrderNewScheme orderNewScheme = handleCustomerMoney(appUser, appOrderDetail);
            //普通分佣方案
            BigDecimal customerMoney = orderNewScheme.getCustomerMoney();
            //订单状态
            Integer tkStatus = Integer.valueOf(appOrderDetail.getPayStatus());
            //构建order
            AppUserOrder appUserOrder = new AppUserOrder();
            appUserOrder.setUserId(appUser.getUserId());
            appUserOrder.setTaobaoUserId(Long.valueOf(appUser.getTaobaoUserId() == null ? 0L : appUser.getTaobaoUserId()));
            appUserOrder.setOrderId(appOrderDetail.getTradeId());
            if (tkStatus == 13) {
                appUserOrder.setCommission(BigDecimalUtils.Format(0));
            } else {
                appUserOrder.setCommission(customerMoney.
                        compareTo(BigDecimal.valueOf(0.01)) < 0 ?
                        BigDecimal.valueOf(0.01) : BigDecimalUtils.Format(customerMoney));
            }
            appUserOrder.setSpareMoney((customerMoney.
                    compareTo(BigDecimal.valueOf(0.01)) < 0 ?
                    BigDecimal.valueOf(0.01) : BigDecimalUtils.Format(customerMoney)).add(BigDecimalUtils.Format(appGoods == null ? 0d : appGoods.getCouponmoney())));
            appUserOrder.setOrderGrade(1);
            appUserOrder.setOrderStatus(tkStatus);
            appUserOrder.setOrderSettleStatus(1);
            appUserOrder.setFreezeDay(8);
            //是否是固定返(1固定返)
            appUserOrder.setOrderType(orderNewScheme.getOrderType() == null ? 0 : 1);
            if (tkStatus == 3 || tkStatus == 14) {
                //查询佣金是否符合佣金冻结设置
                CommissionFreeze freeze = null;
                if (redisTemplateService.hasKey("CommissionFreezeStuep")) {
                    freeze = redisTemplateService.getTByKey("CommissionFreezeStuep", CommissionFreeze.class);
                } else {
                    freeze = iCommissionFreezeService.selectByPrimaryKeyLIMIT(1);
                    redisTemplateService.set("CommissionFreezeStuep", freeze, 60 * 60);
                }
                appUserOrder.setLargeAmountYes(1);
                appUserOrder.setLargeAmountTime(getDateTime(appOrderDetail.getEarningTime(), freeze.getDelaydays()));//延迟天数毫秒
            }

            int i2 = iAppUserOrderService.insertAppUserOrder(appUserOrder);
            log.info("插入用户订单中间表数据是否成功{},：用户id：{}:订单{}: {}", i2, appUser.getUserId(), appOrderDetail.getTradeId(), appOrderDetail.getTkStatus());
            return true;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return false;
        }

    }

    private CountLauncherPay countLauncherPay;

    private CountLauncherFail countLauncherFail;

    private CountLauncherSuccess countLauncherSuccess;

    private CountLauncherDone countLauncherDone;

    private CountLauncherRefund countLauncherRefund;

    @Override
    public CountLauncherPay getCountLauncherPay() {
        return countLauncherPay;
    }

    @Override
    public void setCountLauncherPay(CountLauncherPay countLauncherPay) {
        this.countLauncherPay = countLauncherPay;
    }

    @Override
    public CountLauncherFail getCountLauncherFail() {
        return countLauncherFail;
    }

    @Override
    public void setCountLauncherFail(CountLauncherFail countLauncherFail) {
        this.countLauncherFail = countLauncherFail;
    }

    @Override
    public CountLauncherSuccess getCountLauncherSuccess() {
        return countLauncherSuccess;
    }

    @Override
    public void setCountLauncherSuccess(CountLauncherSuccess countLauncherSuccess) {
        this.countLauncherSuccess = countLauncherSuccess;
    }

    @Override
    public CountLauncherDone getCountLauncherDone() {
        return countLauncherDone;
    }

    @Override
    public void setCountLauncherDone(CountLauncherDone countLauncherDone) {
        this.countLauncherDone = countLauncherDone;
    }

    @Override
    public CountLauncherRefund getCountLauncherRefund() {
        return countLauncherRefund;
    }


    @Override
    public void setCountLauncherRefund(CountLauncherRefund countLauncherRefund) {
        this.countLauncherRefund = countLauncherRefund;
    }

}
